使用–harmony_modules选项,ES2015“导入”不能在节点v6.0.0中工作

我正在使用节点v6.0.0,并希望使用ES2016(ES6)。 但是,我意识到“导入”语法不起作用。 在ES2015中编写模块代码不是“input”的根本吗? 我尝试使用--harmony_modules选项运行节点,但仍然得到了有关“导入”相同的错误。 这是代码。

没有“导入”的工作代码:

 'use strict'; let sum = 0; class Number { addNumber(num1, num2) { return num1 + num2; } } let numberObj = new Number(); sum = numberObj.addNumber(1,2); console.log("sum of two number 1 and 2 "+ sum); 

不带“导入”的代码:

server.js

 'use strict'; import Number from "./Number"; let sum = 0; let numberObj = new Number(); sum = numberObj.addNumber(1,2); console.log("sum of two number 1 and 2 "+ sum); 

Number.js

 'use strict'; export default class Number { addNumber(num1, num2) { return num1 + num2; } } 

我也检查了http://node.green/来查看支持的es6,但不能理解为什么它不能和–harmony_modules选项一起工作。 请帮忙。

他们只是还没有实施。

节点6.0.0使用完成了大部分ES6function的V8版本。 不幸的是,模块不是那些完成的function之一。

 node --v8-options | grep harmony 

进行中和谐标志没有完全实施,通常不起作用:

–es_staging(启用testing值得和谐的function( 仅供内部使用 ))
– 和谐(使所有完成的和声function)
–harmony_shipping(启用所有出货的和声function)
–harmony_object_observe(启用“和谐Object.observe”( 进行中 ))
–harmony_modules (启用“和谐模块”( 进行中 ))
–harmony_function_sent(启用“和谐function。发送”( 进行中 ))
–harmony_sharedarraybuffer(启用“和谐sharedarraybuffer”( 进行中 ))
–harmony_simd(启用“和谐simd”( 进行中 ))
–harmony_do_expressions(启用“和谐doexpression式”( 进行中 ))
–harmony_iterator_close(启用“和谐迭代器完成”( 进行中 ))
–harmony_tailcalls(启用“和声尾呼叫”( 进行中 ))
–harmony_object_values_entries(启用“和谐Object.values / Object.entries”( 进行中 ))
–harmony_object_own_property_descriptors(启用“和谐Object.getOwnPropertyDescriptors()”( 进行中 ))
–harmony_regexp_property(启用“和谐unicode正则expression式属性类”( 进行中 ))
–harmony_function_name(启用“和声function名称推断”)
–harmony_regexp_lookbehind(启用“和谐regexp lookbehind”)
–harmony_species(启用“和谐Symbol.species”)
–harmony_instanceof(启用“和谐instanceof支持”)
–harmony_default_parameters(启用“和谐默认参数”)
–harmony_destructuring_assignment(启用“和谐解构作业”)
–harmony_destructuring_bind(启用“和谐解构绑定”)
–harmony_tostring(启用“和谐toString”)
–harmony_regexps(启用“和谐正则expression式扩展”)
–harmony_unicode_regexps(启用“和声unicode正则expression式”)
–harmony_sloppy(启用“马虎模式下的和声function”)
–harmony_sloppy_let(启用“和谐模式”)
–harmony_sloppy_function(启用“和谐草率function块范围”)
–harmony_proxies(启用“和谐代理”)
–harmony_reflect(启用“和谐反思API”)
–harmony_regexp_subclass(启用“和谐正规expression子类”)

这应该是@ Paulpro的答案的评论,但我没有足够的代表发表评论。

对于Windows用户,等效命令是:

 node --v8-options | findstr harmony 

在模块实现之前,你可以使用Babel“transpiler”来运行你的代码:

 npm install --save babel-cli babel-preset-node6 ./node_modules/.bin/babel-node --presets node6 ./your_script.js 

请参阅https://www.npmjs.com/package/babel-preset-node6和https://babeljs.io/docs/usage/cli/

缺点 :这有不同的缺点,如额外的编译时间,这可能是重要的,你现在需要源地图进行debugging; 只是说。

如上所述,ES6模块尚未实现。

以与当前Node.js模块语法Common JS模块向后兼容的方式实现ES6模块似乎是一个不平凡的问题。

但是,有一个实现草案 ,为包含ES6模块的文件引入了新的文件扩展名 – .mjs

此外,还有一个反提案提出了一个在package.json中用ES6模块声明所有文件的替代方法,如下所示:

 { "modules.root": "/path/to/es6/modules" }