如何在Node.js中使用ES6导入? [英] How can I use an ES6 import in Node.js?
问题描述
我试图在Node.js中停止ES6导入,并尝试使用此示例中提供的语法:
I'm trying to get the hang of ES6 imports in Node.js and am trying to use the syntax provided in this example:
我正在浏览支持表,但是找不到支持的版本新的import语句(我尝试查找文本import / require)。我目前正在运行Node.js 8.1.2,并且还相信,由于备忘单是指.js文件,因此它应该与.js文件一起使用。
I'm looking through the support table, but I was not able to find what version supports the new import statements (I tried looking for the text import/require). I'm currently running Node.js 8.1.2 and also believe that since the cheatsheet is referring to .js files it should work with .js files.
在我运行代码时(来自备忘单的第一个示例):
As I run the code (taken from the cheatsheet's first example):
import { square, diag } from 'lib';
我收到错误:
SyntaxError:意外的令牌导入。
SyntaxError: Unexpected token import.
对我要导入的库的引用:
Reference to library I'm trying to import:
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
我缺少什么以及如何获得 node
识别我的 import
语句?
What am I missing and how can I get node
to recognize my import
statement?
推荐答案
Node.js包括对ES6支持的实验性支持。
在此处了解更多信息: https:// nodejs。 org / docs / latest-v13.x / api / esm.html#esm_enabling 。
TLDR;
Node.js> = v13
在Node.js 13及更高版本中非常简单。您需要:
It's very simple in Node.js 13 and above. You need to either:
- 使用
.mjs
扩展名保存文件,或者 - 添加
{ type: module }
放在最近的package.json
中。
- Save the file with
.mjs
extension, or - Add
{ "type": "module" }
in the nearestpackage.json
.
您只需要执行上述操作之一才能使用ECMAScript模块。
You only need to do one of the above to be able to use ECMAScript modules.
Node.js< = v12
如果您使用的是Node.js版本8-12,请使用扩展名为 .mjs
的ES6模块保存文件并按以下方式运行它:
If you are using Node.js version 8-12, save the file with ES6 modules with .mjs
extension and run it like:
node --experimental-modules my-app.mjs
这篇关于如何在Node.js中使用ES6导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!