我不明白是怎么回事。
节点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
我要在最初的问题中解决另一个问题,没有人问过这个问题。最近在我自己的NodeJS项目中从CommonJS转换到ESM后,我很少看到关于你不能像require那样把导入放在你想要的任何地方的讨论。我的项目现在使用导入工作得很好,但是当我使用问题中的代码时,我首先得到一个没有命名函数的错误。命名函数后,我收到以下…
import express from 'express'
^^^^^^^
SyntaxError: Unexpected identifier
at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
您不能像需要的那样在函数中导入。它们必须放在文件的顶部,在代码块之外。我自己在这个问题上也浪费了不少时间。
因此,虽然上面所有的答案都能很好地帮助您在项目中导入,但没有一个能解决原始问题中的代码不能像编写的那样工作的问题。
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
作为Node.js v12(这可能是相当稳定的现在,但仍然标记为“实验”),你有两个选项使用ESM (ECMAScript模块)在Node.js(文件,有第三种方法计算字符串),以下是文档所说的:
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 by import statements within
ES module code:
Files ending in .mjs.
Files ending in .js, or extensionless files, when the nearest parent
package.json file contains a top-level field "type" with a value of
"module".
Strings passed in as an argument to --eval or --print, or piped to
node via STDIN, with the flag --input-type=module.
Node.js will treat as CommonJS all other forms of input, such as .js files
where the nearest parent package.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 to node as the initial input,
or when referenced by import statements within ES module code:
Files ending in .cjs.
Files ending in .js, or extensionless files, when the nearest parent
package.json file contains a top-level field "type" with a value of
"commonjs".
Strings passed in as an argument to --eval or --print, or piped to
node via STDIN, with the flag --input-type=commonjs.