SyntaxError:从IntellijIDEA启动NodeJS时,无法在模块外部使用import语句 [英] SyntaxError: Cannot use import statement outside a module when start NodeJS from IntellijIDEA

查看:353
本文介绍了SyntaxError:从IntellijIDEA启动NodeJS时,无法在模块外部使用import语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to create hello world applications by react js. I created the NodeJS application in IntelliJ IDEA. Create a helloworld.js file. and add this code to this file

import React from 'react';

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('root')
);

向package.json添加了react-dom依赖关系.发出npm install命令.启动应用程序

Added react-dom dependency to package.json. Made npm install command. Start Application

{
  "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

推荐答案

您正在尝试在Node.js中执行React程序,但它旨在在Web浏览器中运行 . Node.js中没有DOM供您操纵.那只是行不通的.

You're trying to execute a React program in Node.js, but it is designed to run in a web browser. There is no DOM in Node.js for you to manipulate. That just isn't going to work.

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

Since the program you are running uses JSX, you'll need to transpile it before it will work there too.

返回返回教程.关于设置本地开发环境的部分提供了一种方法起步并运行,或者您可以查看

Go back to the tutorial. The section on setting up a local development environment provides an approach to getting up and running or you can look at a selection of toolchains that you can choose from.

这篇关于SyntaxError:从IntellijIDEA启动NodeJS时,无法在模块外部使用import语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆