当我在 WebStorm 中 运行 一个 JavaScript 文件时,说 cannot import statement outside module

When I run a JavaScript file in WebStorm, says as cannot import statement outside module

错误是这样说的 **从 'react';

导入 React,{Component}
SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_enter code heremain_module.js:17:11**

我假设您正在尝试在不使用 create-react-app cli 的情况下从头开始创建您的 React 应用程序。在这种情况下,ES6 导入和导出将不起作用,因为 node.js 不支持开箱即用的 imports/exports。他们目前遵循 CommonJS 模块系统。要实现 ES6 imports/exports,您必须使用 babel 将代码从 ES6 转换为 ES5。或者根据您的节点版本(通常是较新版本),您可能可以尝试一些事情,如以下关于 Whosebug 本身的优秀答案中所述:-

看起来好像您正在尝试 运行 您的 React 应用程序 Node.js,通过右键单击您的组件 .js 文件正在选择 运行。这不应该起作用;您必须 transpile/build 您的应用程序,启动托管它的服务器,然后在浏览器中打开服务器 URL。 对于使用 create-react-app 创建的应用程序,请按照 https://www.jetbrains.com/help/webstorm/2020.1/react.html#react_running_and_debugging

中的说明进行操作