如何在 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:
我正在查看支持表,但找不到支持新导入语句的版本(我尝试寻找文本导入/要求).我目前正在运行 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: 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/最新-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屋!