我试图在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));
}

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


当前回答

如果您在服务器端使用模块系统,则根本不需要使用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.

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

其他回答

如果您在服务器端使用模块系统,则根本不需要使用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.

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

我不知道这是否适用于你的情况,但我正在运行一个Express.js服务器:

nodemon --inspect ./index.js --exec babel-node --presets es2015,stage-2

这使我能够导入和使用扩展操作符,即使我只使用Node.js版本8。

您需要安装babel-cli、babel-预置-es2015和babel-预置-stage-2来完成我正在做的工作。

Use:

  "devDependencies": {
    "@babel/core": "^7.2.0",
    "@babel/preset-env": "^7.2.0",
    "@babel/register": "^7.0.0"
  }

文件 .babelrc

{
  "presets": ["@babel/preset-env"]
}

Node.js应用的入口点:

require("@babel/register")({})

// Import the rest of our application.
module.exports = require('./index.js')

参见如何在Node.js中启用ES6导入

回到Jonathan002最初的问题

“…什么版本支持新的ES6导入语句?”

根据Dr. Axel Rauschmayer的文章,在Node.js 10中有一个默认支持它的计划(没有实验性的命令行标志)。x LTS。根据node.js在2018年3月29日的发布计划,它很可能在2018年4月之后可用,而它的LTS将在2018年10月开始。

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

官方文件指出:

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

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

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