【问题标题】:Using ES6 syntax in Node script with Babel在带有 Babel 的 Node 脚本中使用 ES6 语法
【发布时间】:2016-01-19 16:28:41
【问题描述】:

我有一个使用 BabelJS 的 ES6 语法的 npm CLI 工具。具体来说,我使用的是 ES6 中的箭头函数。

在我的工具入口点中,我有以下要求:

require('babel-core/register');
var program = require('./modules/program.js');

我在根目录下还有一个.babelrc 文件,看起来像这样:

{ "presets": ["es2015"] }

在这种情况下,program.js 是完成大部分繁重工作的地方。在这个文件中有一个箭头函数,如:

arrayOfStrings.forEach((substr) => {
    console.log(substr);
});

如果我使用以下命令运行此工具,它就可以正常工作。

node index.js --options

但是,如果我使用npm publish 发布此工具并像这样运行它:

tool-name --options

我得到这个错误:

/usr/local/lib/node_modules/unfollow/modules/program.js:134
    arrayOfStrings.forEach((substr) => {
                             ^^
SyntaxError: Unexpected token =>
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Module._extensions..js (module.js:478:10)
    at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/tool-name/node_modules/babel-core/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/tool-name/index.js:7:15)
    at Module._compile (module.js:460:26)

有人知道为什么会这样吗?

【问题讨论】:

  • FWIW,Node v4+ 原生支持箭头函数
  • @FelixKling 很有趣!所以升级我的节点版本确实有效,但我仍然很好奇为什么会失败。

标签: javascript node.js npm ecmascript-6 babeljs


【解决方案1】:

babel-register 仅用于简化本地开发,不适用于分布式包。如果你在为 npm 做东西,你应该事先将它编译成 ES5。

【讨论】:

  • 你是对的。你知道当你读到一些东西时,你就会意识到你的整体心态是错误的。这为我做到了。谢谢,@loganfsmyth。
猜你喜欢
  • 2019-02-12
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2017-09-15
相关资源
最近更新 更多