node8.5 使用import提示SyntaxError: Unexpected token import
代码结构:
demo.mjs
export function add(x, y) {
return x + y;
}
main.mjs
import { add } from './demo.mjs';
console.log('Result: '+add(2, 3));
执行命令:node .\main.mjs --experimental-modules 错误提示:
(function (exports, require, module, __filename, __dirname) { import { add } from './demo.mjs';
{ add } from './demo.mjs';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:201:16)
at bootstrap_node.js:626:3
8 回复
–experimental-modules要写在前面
node --experimental-modules .\main.mjs
(node:8624) ExperimentalWarning: The ESM module loader is experimental.
{ AssertionError [ERR_ASSERTION]: An invalid error message key was used: ERR_INVALID_PROTOCOL.
at message (internal/errors.js:70:3)
at NodeError (internal/errors.js:29:13)
at resolveRequestUrl (internal/loader/resolveRequestUrl.js:84:11)
at Loader.import (internal/loader/Loader.js:61:27)
at Function.Module._load (module.js:462:27)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:201:16)
at bootstrap_node.js:626:3
generatedMessage: false,
name: 'AssertionError [ERR_ASSERTION]',
code: 'ERR_ASSERTION',
actual: undefined,
expected: true,
operator: '==' }
@zhang8longfei 去 Nodejs github 上提 issues,目前这个有很多 bug。
@zhang8longfei windows上暂时有bug不能用,linux上可以
最新的8.6.0版本已经修复了windows下的这个bug,可以尝试使用了
@dislido 已从windows换mac了
我也遇到了这个错误,请问目前解决了吗
@dislido 我用8.9.1 怎么也报这个错:( SyntaxError: Unexpected token import