SyntaxError:从 IntellijIDEA 启动 NodeJS 时不能在模块外使用 import 语句

Pav*_*hov 6 javascript intellij-idea node.js reactjs

我尝试通过 react js 创建 hello world 应用程序。我在 IntelliJ IDEA 中创建了 NodeJS 应用程序。创建一个 helloworld.js 文件。并将此代码添加到此文件中

import React from 'react';

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

向 package.json 添加了 react-dom 依赖项。制作了 npm install 命令。开始申请

{
  "name": "testjsapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react-dom": "^16.12.0"
  }
}
Run Code Online (Sandbox Code Playgroud)

错误:

"C:\Program Files\nodejs\node.exe" D:\projects\testjsapp\hello\helloworld.js
D:\projects\testjsapp\hello\helloworld.js:2
import React from 'react';
^^^^^^

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_main_module.js:17:11

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 6

您正在尝试在 Node.js 中执行 React 程序,但它被设计为在 Web 浏览器中运行。Node.js 中没有 DOM 供您操作。那是行不通的。

由于您正在运行的程序使用 JSX,因此您需要对其进行转译,然后它才能在其中运行。

返回教程。关于设置本地开发环境的部分提供了一种启动和运行的方法,或者您可以查看可供选择的工具链。