我不明白是怎么回事。
节点v5.6.0
NPM v3.10.6
代码:
function (exports, require, module, __filename, __dirname) {
import express from 'express'
};
错误:
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
正如在其他回答中提到的,Node JS目前不支持ES6导入。
(从现在开始,请阅读EDIT 2)
在node js中启用ES6导入可以解决这个问题。我试过这个方法,对我很有效。
执行如下命令:
npm install babel-register babel-preset-env --save-dev
现在需要创建一个新文件(config.js),并向其中添加以下代码。
require('babel-register')({
presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')
现在您可以编写import语句而不会得到任何错误。
希望这能有所帮助。
编辑:
您需要运行使用上述代码创建的新文件。我用的是config.js。所以我得跑了:
node config.js
编辑2:
在试验过程中,我发现了一个简单的解决方法。
在项目的根目录下创建.babelrc文件。
添加以下(和任何其他你需要的babel预设,可以添加在这个文件中):
{
"presets": ["env"]
}
使用npm Install babel-pre -env——save命令安装babel-cli,然后使用npm Install babel-cli -g——save命令安装babel-cli
现在,转到服务器或索引文件所在的文件夹,使用以下命令运行:
babel-node fileName.js
或者你也可以使用npm start运行,在你的包中添加以下代码。json文件:
"scripts": {
"start": "babel-node src/index.js"
}
My project uses node v10.21.0, which still does not support ES6 import keyword. There are multiple ways to make node recognize import, one of them is to start node with node --experimental-modules index.mjs (The mjs extension is already covered in one of the answers here). But, this way, you will not be able to use node specific keyword like require in your code. If there is need to use both nodejs's require keyword along with ES6's import, then the way out is to use the esm npm package. After adding esm package as a dependency, node needs to be started with a special configuration like: node -r esm index.js