Javascript Node.js - 语法错误:意外的令牌导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39436322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js - SyntaxError: Unexpected token import
提问by SofDroid
I don't understand what is wrong. Node v5.6.0 NPM v3.10.6
我不明白出了什么问题。节点 v5.6.0 NPM v3.10.6
The code:
编码:
function (exports, require, module, __filename, __dirname) {
import express from 'express'
};
The error:
错误:
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
回答by Scimonster
Update 3:Since Node 13, you can use either the .mjs extension, or set "type": "module" in your package.json. You don'tneed to use the --experimental-modules
flag.
更新 3:从Node 13 开始,您可以使用 .mjs 扩展名,也可以在 package.json 中设置“type”:“module”。你并不需要使用--experimental-modules
标志。
Update 2:Since Node 12, you can use either the .mjs
extension, or set "type": "module"
in your package.json. And you need to run node with the --experimental-modules
flag.
更新 2:从Node 12 开始,您可以使用.mjs
扩展名,也可以"type": "module"
在 package.json 中进行设置。并且您需要使用--experimental-modules
标志运行节点。
Update:In Node 9, it is enabled behind a flag, and uses the .mjs
extension.
更新:在Node 9 中,它在一个标志后面启用,并使用.mjs
扩展。
node --experimental-modules my-app.mjs
While import
is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.
虽然import
它确实是 ES6 的一部分,但遗憾的是,NodeJS 默认还不支持它,并且直到最近才在浏览器中获得支持。
See browser compat table on MDNand this Node issue.
请参阅MDN 上的浏览器兼容性表和此节点问题。
From James M Snell's Update on ES6 Modules in Node.js(February 2017):
来自 James M Snell对 Node.js 中 ES6 模块的更新(2017 年 2 月):
Work is in progress but it is going to take some time?—?We're currently looking at around a year at least.
工作正在进行中,但需要一些时间?-?我们目前至少在一年左右。
Until support shows up natively, you'll have to continue using classic require
statements:
在原生支持出现之前,您必须继续使用经典require
语句:
const express = require("express");
If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel. Here's an example server.
如果你真的想在 NodeJS 中使用新的 ES6/7 特性,你可以使用 Babel 编译它。这是一个示例服务器。
回答by baranskistad
Unfortunately, Node.js doesn't support ES6's import
yet.
不幸的是,Node.js 还不支持 ES6 import
。
To accomplish what you're trying to do (import the Express module), this code should suffice
为了完成你想要做的事情(导入 Express 模块),这段代码就足够了
var express = require("express");
Also, be sure you have Express installed by running
另外,请确保您通过运行安装了 Express
$ npm install express
See the Node.js Docsfor more information about learning Node.js.
有关学习 Node.js 的更多信息,请参阅Node.js 文档。
回答by Neerali Acharya
As mentioned in other answers Node JS currently doesn't support ES6 imports.
正如其他答案中提到的,Node JS 目前不支持 ES6 导入。
(As of now, read EDIT 2)
(截至目前,阅读编辑 2)
Enable ES6 imports in node jsprovides a solution to this issue. I have tried this and it worked for me.
在 node js 中启用 ES6 导入提供了解决此问题的方法。我试过这个,它对我有用。
Run the command:
运行命令:
npm install babel-register babel-preset-env --save-dev
Now you need to create a new file (config.js) and add the following code to it.
现在您需要创建一个新文件 (config.js) 并向其中添加以下代码。
require('babel-register')({
presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')
Now you can write import statements without getting any errors.
现在您可以编写导入语句而不会出现任何错误。
Hope this helps.
希望这可以帮助。
EDIT:
编辑:
You need to run the new file which you created with above code. In my case it was config.js
. So I have to run:
您需要运行使用上述代码创建的新文件。就我而言,它是config.js
. 所以我必须运行:
node config.js
EDIT 2:
编辑2:
While experimenting, I found one easy solution to this issue.
在试验过程中,我找到了一个简单的解决方案来解决这个问题。
Create .babelrc
file in the root of your project.
.babelrc
在项目的根目录中创建文件。
Add following (and any other babel presets you need, can be added in this file):
添加以下内容(以及您需要的任何其他 babel 预设,可以添加到此文件中):
{
"presets": ["env"]
}
Install babel-preset-env
using command npm install babel-preset-env --save
, and then install babel-cli
using command npm install babel-cli -g --save
babel-preset-env
使用命令安装npm install babel-preset-env --save
,然后babel-cli
使用命令安装npm install babel-cli -g --save
Now, go to the folder where your server or index file exists and run using: babel-node fileName.js
现在,转到您的服务器或索引文件所在的文件夹并使用以下命令运行: babel-node fileName.js
Or you can run using npm start
by adding following code to your package.json
file:
或者您可以npm start
通过将以下代码添加到您的package.json
文件来运行 using :
"scripts": {
"start": "babel-node src/index.js"
}
回答by supritshah1289
Error:SyntaxError: Unexpected token importor SyntaxError: Unexpected token export
错误:语法错误:意外的令牌导入或语法错误:意外的令牌导出
Solution:Change all your imports as example
解决方案:更改所有导入作为示例
const express = require('express');
const webpack = require('webpack');
const path = require('path');
const config = require('../webpack.config.dev');
const open = require('open');
And also change your export default = foo;
to module.exports = foo;
也改变你export default = foo;
的module.exports = foo;
回答by thedanotto
I'm shocked esm
hasn't been mentioned. This small, but mighty package allows you to use either import
or require
.
我很震惊esm
没有被提及。这个小而强大的包允许您使用import
或require
。
Install esm in your project
在你的项目中安装 esm
$ npm install --save esm
$ npm install --save esm
Update your Node Start Script to use esm
更新您的节点启动脚本以使用 esm
node -r esm app.js
node -r esm app.js
esm
just works. I wasted a TON of time with .mjs
and --experimental-modules
only to find out a .mjs
file cannot import a file that uses require
or module.exports
. This was a huge problem, whereas esm
allows you to mix and match and it just figures it out... esm
just works.
esm
只是工作。我浪费的时间TON与.mjs
和--experimental-modules
只找出一个.mjs
文件无法导入文件使用require
或module.exports
。这是一个巨大的问题,而esm
允许您混合和匹配,它只是想通了......esm
只是有效。
回答by Alberto
In case that you still can't use "import" here is how I handled it: Just translate it to a node friendly require. Example:
如果您仍然无法使用“导入”,我是这样处理的:只需将其转换为节点友好的需求即可。例子:
import { parse } from 'node-html-parser';
Is the same as:
是相同的:
const parse = require('node-html-parser').parse;
回答by Jason Ashley
babel 7 proposalcan you add dev dependencies
babel 7 提案可以添加开发依赖吗
npm i -D @babel/core @babel/preset-env @babel/register
and add a .babelrc in the root
并在根目录中添加一个 .babelrc
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
}
and add to the .js file
并添加到 .js 文件
require("@babel/register")
or if you run it in the cli, you could use the require hook as -r @babel/register, ex.
或者如果你在 cli 中运行它,你可以使用 require 钩子作为 -r @babel/register,例如。
$node -r @babel/register executeMyFileWithESModules.js
回答by ASTOMUSIC
if you can use 'babel', try to add build scripts in package.json(--presets=es2015) as below. it make to precompile import code to es2015
如果您可以使用 'babel',请尝试在 package.json(--presets=es2015) 中添加构建脚本,如下所示。它使预编译导入代码到 es2015
"build": "babel server --out-dir build --presets=es2015 && webpack"
回答by T.J. Crowder
As of Node.js v12 (and this is probably fairly stable now, but still marked "experimental"), you have a couple of options for using ESM (ECMAScript Modules) in Node.js (for files, there's a third way for evaling strings), here's what the documentationsays:
随着Node.js的V12的(这是现在可能还算稳定,但仍标有“实验性”),你有两个选择使用ESM(ēCMA小号CRIPT中号在Node.js的odules)(的文件,有一个评估字符串的第三种方法),这是文档所说的:
The
--experimental-modules
flag can be used to enable support for ECMAScript modules (ES modules).Once enabled, Node.js will treat the following as ES modules when passed to
node
as the initial input, or when referenced byimport
statements within ES module code:
Files ending in
.mjs
.Files ending in
.js
, or extensionless files, when the nearest parentpackage.json
file contains a top-level field"type"
with a value of"module"
.Strings passed in as an argument to
--eval
ornode
viaSTDIN
, with the flag--input-type=module
.Node.js will treat as CommonJS all other forms of input, such as
.js
files where the nearest parentpackage.json
file contains no top-level"type"
field, or string input without the flag--input-type
. This behavior is to preserve backward compatibility. However, now that Node.js supports both CommonJS and ES modules, it is best to be explicit whenever possible. Node.js will treat the following as CommonJS when passed tonode
as the initial input, or when referenced byimport
statements within ES module code:
Files ending in
.cjs
.Files ending in
.js
, or extensionless files, when the nearest parentpackage.json
file contains a top-level field"type"
with a value of"commonjs"
.Strings passed in as an argument to
--eval
ornode
viaSTDIN
, with the flag--input-type=commonjs
.
该
--experimental-modules
标志可用于启用对 ECMAScript 模块(ES 模块)的支持。启用后,Node.js 将在作为
node
初始输入传递给以下内容时,或import
在 ES 模块代码中的语句引用时将以下内容视为 ES 模块 :
结尾的文件
.mjs
。结尾的文件
.js
,或名的文件,当最近的父package.json
文件中包含顶级场"type"
用的值"module"
。字符串作为参数传递给
--eval
ornode
通过管道传递给 viaSTDIN
,带有标志--input-type=module
。Node.js 会将所有其他形式的输入视为 CommonJS,例如
.js
最近的父package.json
文件不包含顶级"type"
字段的文件,或没有标志的字符串输入--input-type
。此行为是为了保持向后兼容性。然而,现在 Node.js 同时支持 CommonJS 和 ES 模块,最好尽可能明确。当node
作为初始输入传递给 Node.js或被import
ES 模块代码中的语句引用时,Node.js 会将以下内容视为 CommonJS :
结尾的文件
.cjs
。结尾的文件
.js
,或名的文件,当最近的父package.json
文件中包含顶级场"type"
用的值"commonjs"
。字符串作为参数传递给
--eval
ornode
通过管道传递给 viaSTDIN
,带有标志--input-type=commonjs
。
回答by Ashok
When I was started with express always wanted a solution to use import instead require
当我开始使用 express 时,我一直想要一个使用 import 而不是 require 的解决方案
const express = require("express");
// to
import express from "express"
Many time go through this line:- Unfortunately, Node.js doesn't support ES6's import yet.
很多时候通过这条线:- Unfortunately, Node.js doesn't support ES6's import yet.
Now to help other I create new two solutions here
现在为了帮助其他人,我在这里创建了两个新的解决方案
1) esm:-
1) esm:-
The brilliantly simple, babel-less, bundle-less ECMAScript module loader. let's make it work
非常简单、无 babel、无包的 ECMAScript 模块加载器。让我们让它发挥作用
yarn add esm / npm install esm
create start.js or use your namespace
创建 start.js 或使用您的命名空间
require = require("esm")(module/*, options*/)
// Import the rest of our application.
module.exports = require('./src/server.js')
// where server.js is express server start file
Change in your package.josn
pass path of start.js
改变你的package.josn
通行证路径start.js
"scripts": {
"start": "node start.js",
"start:dev": "nodemon start.js",
},
"dependencies": {
+ "esm": "^3.2.25",
},
"devDependencies": {
+ "nodemon": "^1.19.2"
}
2) Babel js:-
2)巴别 js:-
This can be divide into 2 part
这可以分为 2 部分
a) Solution 1thanks to timonweb.com
a)解决方案 1感谢 timonweb.com
b) Solution 2
b)解决方案 2
use Babel 6(older version of babel-preset-stage-3 ^6.0)
create .babelrc
file at your root folder
使用Babel 6(旧版本的babel-preset-stage-3 ^6.0).babelrc
在你的根文件夹中创建文件
{
"presets": ["env", "stage-3"]
}
Install babel-preset-stage-3
安装 babel-preset-stage-3
yarn add babel-cli babel-polyfill babel-preset-env bable-preset-stage-3 nodemon --dev
Change in package.json
更改 package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build"
},
"devDependencies": {
+ "babel-cli": "^6.26.0",
+ "babel-polyfill": "^6.26.0",
+ "babel-preset-env": "^1.7.0",
+ "babel-preset-stage-3": "^6.24.1",
+ "nodemon": "^1.19.4"
},
Start your server
启动你的服务器
yarn start / npm start
Oooh no we create new problem
哦不,我们创造了新问题
regeneratorRuntime.mark(function _callee(email, password) {
^
ReferenceError: regeneratorRuntime is not defined
This error only come when you use async/await in your code.
Then use polyfill that includes a custom regenerator runtime and core-js.
add on top of index.js
只有在代码中使用 async/await 时才会出现此错误。然后使用包含自定义再生器运行时和 core-js 的 polyfill。添加在上面index.js
import "babel-polyfill"
This allow you to use async/await
这允许您使用 async/await
use Babel 7
使用巴别塔 7
Need to upto date every thing in your project let start with babel 7 .babelrc
需要更新项目中的所有内容让我们从 babel 7 .babelrc 开始
{
"presets": ["@babel/preset-env"]
}
Some change in package.json
package.json 中的一些更改
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build",
....
}
"devDependencies": {
+ "@babel/cli": "^7.0.0",
+ "@babel/core": "^7.6.4",
+ "@babel/node": "^7.0.0",
+ "@babel/polyfill": "^7.0.0",
+ "@babel/preset-env": "^7.0.0",
+ "nodemon": "^1.19.4"
....
}
and use import "@babel/polyfill"
on start point
并import "@babel/polyfill"
在起点使用
import "@babel/polyfill"
import express from 'express'
const app = express()
//GET request
app.get('/', async (req, res) {
// await operation
res.send('hello world')
})
app.listen(4000, () => console.log(' Server listening on port 400!'))
Are you thinking why start:dev
你在想为什么 start:dev
Seriously. It is good question if you are new. Every change you are boar with start server every time
then use yarn start:dev
as development server every change restart server automatically for more on nodemon
严重地。如果你是新手,这是个好问题。每次更改您都使用启动服务器,然后将其yarn start:dev
用作开发服务器,每次更改都会自动重新启动服务器以获取更多关于nodemon 的信息