How to run Node.js app with ES6 features enabled?

2019-01-12 21:23发布

I use the require hook of BabelJS (formerly named 6to5) to run node apps with es6features:

// run.js
require("babel/register");
require("./app.js6");

I call node run.js to run my app.js6. I need to install BabelJS and provide a run.js for each project I'd like to use es6features. I would prefer a call like nodejs6 app.js6. How can I achieve this system independently (Unix and Windows)?

8条回答
一夜七次
2楼-- · 2019-01-12 21:37
We Are One
3楼-- · 2019-01-12 21:42

You can use node with --harmony flag to run script with es6 features

查看更多
Anthone
4楼-- · 2019-01-12 21:42

you need to install babel-register and babel-preset-es2015 preset Which used into babel-register options to Enabled convert ES6 to ES5 on-the-fly transpilation

 npm install babel-register

 npm install babel-preset-es2015

your run.js file:

// require babel-register and set Babel presets options to es2015
require('babel-register')({
   presets: [ 'es2015' ]
});

require("./app.js6");

Notice: Now you does not need .babelrc file to set Babel presets options As we setting it with require method

查看更多
仙女界的扛把子
5楼-- · 2019-01-12 21:46

I would prefer a call like nodejs6 app.js6.

You may try the wrapper solution with babel-core api:

// Save as es6.js

var babel = require("babel-core");
var argc = process.argv.length;

babel.transformFile(process.argv[argc - 1], function (err, result) {
    eval(result.code);
});

Run your es6 featured script with node es6 thefile.js

Reference: offical usage doc

查看更多
Viruses.
6楼-- · 2019-01-12 21:46

As of babel 6, you now must install babel-register and use the following

require("babel-register");

Be sure to also install the babel es2015 preset.

查看更多
走好不送
7楼-- · 2019-01-12 21:48

Add the babel-cli and babel-preset-es2015 (aka ES6) dependencies to your app's package.json file and define a start script:

{
  "dependencies": {
    "babel-cli": "^6.0.0",
    "babel-preset-es2015": "^6.0.0"
  },
  "scripts": {
    "start": "babel-node --presets es2015 app.js"
  }
}

Then you can simply execute the following command to run your app:

npm start

If you ever decide to stop using Babel (e.g. once Node.js supports all ES6 features), you can just remove it from package.json:

{
  "dependencies": {},
  "scripts": {
    "start": "node app.js"
  }
}

One benefit of this is that the command to run your app remains the same, which helps if you are working with other developers.

查看更多
登录 后发表回答