如何启用node.js
Many tutorials now use the import XXX from 'XXX'
(ES Modules) syntax instead of const XXX = require('XXX')
(CommonJS) syntax.
现在,许多教程使用import XXX from 'XXX'
( ES模块 )语法import XXX from 'XXX'
而不是使用const XXX = require('XXX')
( CommonJS )语法。
If you add that to your Node.js app, it won’t work. You’ll get an error like this:
如果将其添加到Node.js应用程序,它将无法正常工作。 您将收到如下错误:
unexpected identifier..
unexpected identifier..
One of the solutions to this is to use Babel. If you already have a Babel setup for your project, this should already be working for you.
解决此问题的方法之一就是使用Babel 。 如果您已经为您的项目准备了Babel设置,那么它应该已经为您工作。
But you shouldn’t need Babel any more now because Node has experimental support for ES Modules, and since it’s experimental, to enable it you must do 3 things.
但是,您现在不再需要Babel,因为Node具有对ES模块的实验性支持,并且由于它是实验性的,要使其具备功能,您必须做三件事。
First, install the latest version of Node.js. It has the latest and greatest features.
首先,安装最新版本的Node.js。 它具有最新和最强大的功能。
Second, add the "type": "module"
line in your package.json
file.
其次,在package.json
文件中添加"type": "module"
行。
Third, use the --experimental-modules
flag when invoking nodejs
:
第三,在调用nodejs
时使用--experimental-modules
标志:
node --experimental-modules app.js
You should be good to go!
你应该很好走!
An alternative is to avoid adding the "type": "module"
line in your package.json
file and instead rename your app.js
file (or whatever) to app.mjs
.
一种替代方法是避免在package.json
文件中添加"type": "module"
行,而将您的app.js
文件(或其他名称)重命名为app.mjs
。
Note that now the require()
syntax will stop working.
请注意,现在require()
语法将停止工作。
For older Node.js versions that might not support this flag, I recommend checking out the esm
npm module.
对于可能不支持此标志的旧版Node.js,建议您检查esm
npm模块 。
翻译自: https://flaviocopes.com/how-to-enable-es-modules-nodejs/
如何启用node.js