我试图在Node.js中获得ES6导入的窍门,并试图使用本示例中提供的语法:

Cheatsheet链接

我正在查看支持表,但我无法找到支持新的导入语句的版本(我尝试寻找文本import/require)。我目前正在运行Node.js 8.1.2,也相信由于备考表引用的是.js文件,它应该与.js文件一起工作。

当我运行代码时(摘自备忘单的第一个例子):

import { square, diag } from 'lib';

我得到了错误:

SyntaxError:意外的令牌导入。

引用库,我试图导入:

//------ 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));
}

我错过了什么,我如何才能让节点识别我的导入语句?


当前回答

解决方案

https://www.npmjs.com/package/babel-register

// This is to allow ES6 export syntax
// to be properly read and processed by node.js application
require('babel-register')({
  presets: [
    'env',
  ],
});

// After that, any line you add below that has typical ES6 export syntax
// will work just fine

const utils = require('../../utils.js');
const availableMixins = require('../../../src/lib/mixins/index.js');

下面是mixins/index.js文件的定义

export { default as FormValidationMixin } from './form-validation'; // eslint-disable-line import/prefer-default-export

这在我的Node.js CLI应用程序中工作得很好。

其他回答

你也可以使用名为esm的npm包,它允许你在Node.js中使用ES6模块。它不需要配置。使用esm,您将能够在JavaScript文件中使用导出/导入。

在终端上运行以下命令

yarn add esm

or

npm install esm

之后,在使用node启动服务器时需要使用这个包。例如,如果您的节点服务器运行index.js文件,您将使用该命令

node -r esm index.js

你也可以把它添加到你的包中。这样的Json文件

{
  "name": "My-app",
  "version": "1.0.0",
  "description": "Some Hack",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node -r esm index.js"
  },

}

然后在终端上运行这个命令来启动节点服务器

npm start

查看这个链接了解更多细节。

Node.js已经包含了对ES6支持的实验性支持。 更多信息请访问:https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling。

TLDR;

Node.js >= v13

这在Node.js 13及以上版本中非常简单。你需要:

保存扩展名为.mjs或 在最近的package.json中添加{"type": "module"}。

您只需要执行上面的其中一项,就可以使用ECMAScript模块。

Node.js <= v12

如果你使用的是Node.js 9.6 - 12版本,保存带有.mjs扩展名的ES6模块文件,并像这样运行它:

node --experimental-modules my-app.mjs

你可以试试esm。

这里有一些介绍:esm

如果您在服务器端使用模块系统,则根本不需要使用Babel。要在Node.js中使用模块,请确保:

使用支持——experimental-modules标志的node版本 你的*.js文件必须重命名为*.mjs

就是这样。

However and this is a big however, while your shinny pure ES6 code will run in an environment like Node.js (e.g., 9.5.0) you will still have the craziness of transpilling just to test. Also bear in mind that Ecma has stated that release cycles for JavaScript are going to be faster, with newer features delivered on a more regular basis. Whilst this will be no problems for single environments like Node.js, it's a slightly different proposition for browser environments. What is clear is that testing frameworks have a lot to do in catching up. You will still need to probably transpile for testing frameworks. I'd suggest using Jest.

还要注意捆绑框架。你会在那里遇到问题。

使用.mjs扩展名(在已接受的答案中建议)来启用ECMAScript模块。然而,使用Node.js v12,你也可以在你的包中全局启用这个特性。json文件。

官方文件指出:

.js和无扩展文件的import语句被视为ES模块,如果最近的父包。Json包含“type”:“module”。

{
  "type": "module",
  "main": "./src/index.js"
}

(当然,在启动应用程序时,仍然需要提供标记——experimental-modules。)