我试图在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.
还要注意捆绑框架。你会在那里遇到问题。