Zack
Zack

Reputation: 677

Using ES6 syntax in Node script with Babel

I have an npm CLI tool that is using ES6 syntax from BabelJS. Specifically, I am using arrow functions from 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:

{ "presets": ["es2015"] }

In this instance, program.js is where most of the heavy lifting is done. 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:

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?

Upvotes: 0

Views: 374

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161657

babel-register is only meant to simplify local development, not for distributed packages. If you are making something for npm, you should compile it to ES5 beforehand.

Upvotes: 2

Related Questions