我不明白哪里出了问题。 Node 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 13+ 自 Node 13 ,您可以使用 .mjs
扩展名,或在您的 package.json 中设置 {"type": "module"}
。您不需要使用--experimental-modules
标志。 Modules is now marked as stable in node.js
Node 12 自 Node 12 ,您可以使用 .mjs
扩展名,或在您的 package.json 中设置 "type": "module"
。并且您需要使用 --experimental-modules
标志运行 Node 。
Node 9 在 Node 9 ,它在标志后面启用,并使用 .mjs
扩展名。
node --experimental-modules my-app.mjs
虽然 import
确实是 ES6 的一部分,但 不幸的是,默认情况下 NodeJS 还不支持它,并且最近才在浏览器中获得支持。
参见 browser compat table on MDN和 this Node issue .
来自 James M Snell 的 Update on ES6 Modules in Node.js (2017 年 2 月):
Work is in progress but it is going to take some time — We’re currently looking at around a year at least.
在原生支持 ( now marked stable in Node 13+ ) 出现之前,您必须继续使用经典的 :require
语句
const express = require("express");
如果你真的想在 NodeJS 中使用新的 ES6/7 特性,你可以使用 Babel 编译它。 Here's an example server .
关于javascript - Node.js - 语法错误 : Unexpected token import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197386/