简体   繁体   English

使用Babel在Node脚本中使用ES6语法

[英]Using ES6 syntax in Node script with Babel

I have an npm CLI tool that is using ES6 syntax from BabelJS. 我有一个使用BabelJS的ES6语法的npm CLI工具。 Specifically, I am using arrow functions from ES6. 具体来说,我正在使用ES6中的箭头功能。

In my entry point to the tool, I have the following require: 在该工具的入口点,我有以下要求:

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

I also have a .babelrc file in root that looks like such: 我在根目录中也有一个.babelrc文件,如下所示:

{ "presets": ["es2015"] }

In this instance, program.js is where most of the heavy lifting is done. 在这种情况下,大部分繁重的工作都在program.js上完成。 And in this file there is an arrow function like: 在此文件中有一个箭头函数,例如:

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

If I run this tool with the following command, it works just fine. 如果我使用以下命令运行此工具,则它可以正常工作。

node index.js --options

However, if I publish this tool with npm publish and run it like so: 但是,如果我使用npm publish发布此工具, npm publish运行它:

tool-name --options

I get this error: 我收到此错误:

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

Does anyone know why this could be? 有谁知道为什么会这样吗?

babel-register is only meant to simplify local development, not for distributed packages. babel-register仅用于简化本地开发,不适用于分布式软件包。 If you are making something for npm, you should compile it to ES5 beforehand. 如果要为npm制作东西,则应事先将其编译为ES5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM