我尝试通过 react js 创建 hello world 应用程序。我在 IntelliJ IDEA 中创建了 NodeJS 应用程序。创建一个 helloworld.js 文件。并将此代码添加到此文件
import React from 'react';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
向 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"
}
}
错误:
"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
原文由 Pavel Petrashov 发布,翻译遵循 CC BY-SA 4.0 许可协议
你试图在 Node.js 中执行一个 React 程序,但它被设计为 在网络浏览器中 运行。 Node.js 中没有 DOM 供您操作。那是行不通的。
由于您正在运行的程序使用 JSX,因此您需要先转换它才能在那里工作。
返回 教程。 关于设置本地开发环境的部分提供了启动和运行的方法,或者您可以查看可供选择 的一系列工具链。