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

10

83

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

Beach answered 28/2, 2015 at 14:10 Comment(6)
Have you considered using io.js instead of NodeJS+Babel? iojs.org/en/index.htmlMonstrance
I didn't know io.js. Looks great, but unlike BabelJS it doesn't support rest arguments.Beach
Right. Well keep an eye on it, it's moving fast unlike NodeJS so I'm sure it'll be supported soon.Monstrance
Are you looking for babel-node? babeljs.io/docs/usage/cli/#babel-nodeOssuary
Might want to check out npmjs.com/package/babel-register-cliStacystadholder
Simple solution successfull with node 13.5, express 6.13.4 timonweb.com/tutorials/…Villanovan
L
145

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.

Laliberte answered 2/4, 2015 at 14:20 Comment(6)
It should be noted that the babel docs explicitly warn against using babel-node in production.Fogdog
What about nodemon or others with your settings? Are you really reload server manually every time you make changes to files while developing?Spiritualism
From the docs: You should not be using babel-node in production. It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. You will also always experience a startup performance penalty as the entire app needs to be compiled on the fly.Polinski
Update: es of 2017, the preferable common preset is preset-env. And as long, as that is installed, it doesn't even need to be specified...Welkin
...thus, as long as babel-cli and preset-env is installed, and if you like things directly (w/o npm run... and the package.json-editing required) the command (issued from project root) is: $> ./node_modules/.bin/babel-node yourToolhere.jsWelkin
Why would i need all those dependencies just to run a certain js versionSybarite
A
39

How configure node.js app with es6 support and server reload on file change.


I.Configuration steps ( creating project from the scratch ):

1.Go in terminal to Your project main directory

npm init //create package.json for project

2.Install dependencies

npm install --save-dev babel
npm install --save-dev babel-cli
npm install --save-dev babel-preset-es2015
npm install --save-dev babel-preset-stage-0 //*1
npm install --save-dev nodemon

1 - it can be also stage-1 or 2, it depends what features of es We want to use

3.We should have in package.json file something like that ( for sure package version will be different but it is ok ):

"devDependencies": {
  "babel": "^6.5.2",
  "babel-cli": "^6.16.0",
  "babel-preset-es2015": "^6.16.0",
  "babel-preset-stage-0": "^6.16.0",
  "nodemon": "^1.11.0"
}

4.Create .babelrc file in root project directory ( there is package.json file )

{
 "presets": ["es2015", "stage-0"]
}

5.Create two directories:

src - here is working directory with files writen in es6

dist - here files will compile to es5 using babel

Your project root directory should look like this:

  • project
    • src
      • index.js //main project file
    • dist
    • package.json
    • .babelrc

7.Add to package.json needed commands:

"scripts": {
  "watch": "babel -w src/ -d dist/",
  "build": "babel src/ -d dist/",
  "serve": "babel -w src/ -d dist/ | nodemon --watch dist",
  "test": "echo \"Error: no test specified\" && exit 1"
}

8.Available commands:

npm run watch //starts watch watch changes in src directory and compiles in to dist

npm run build //compiles files from src directory to dist

npm run serve //it is doing watch + start node server, on every file change it will restart node server using nodemon which is watching dist directory changes

9.Final notes

  • Server will run dist/index.js file as main file.
  • File dist/index.js will be compiled from src/index.js so there should be main file of project.
  • dist directory should be added to ignore by git ( but not ignore it for npm if it will be a node package )

10.Run server and start creating app in src directory.

npm run serve

II. Easier way ( ready to use boilerplate )

If it is too many points for You then full woking boilerplate is available on github - https://github.com/maciejsikora/node-express-babel-boilerplate.

Achromatous answered 20/10, 2016 at 8:21 Comment(3)
the problem this transpilation just convert the js files and does not include the node modules insideGirondist
create second build command like - "build-modules": "babel node-modules/ -d dist/",Achromatous
According to the babel itself, babel package, is a no-op in Babel 6. Babel's CLI commands have been moved from the babel package to the babel-cli package. Consider installing @babel/core and @babel/cli instead. Change the scripts to "babel src -d dist"Pylle
W
17

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

Wangle answered 28/2, 2015 at 16:53 Comment(2)
Node with --harmony flag doesn't support rest arguments. A feature that is supported by BabelJS and that I'd like to use.Beach
You can see that rest parameters are supported now kangax.github.io/compat-table/es6/#node8_10Domineca
C
7
  1. node -r babel-register scripts.js

This is the best solution

  1. npx babel-node scripts.js

!Babel node doesn't work well in case of exit process and kexec package also doesn't help in this case (as I tried)

In both cases you need to use .babelrc which should describe presets and plugins for your app.

npx is using only for execution of libraries which are not installed with npm or yarn . Otherwise you need to npm i -g babel-cli and then babel-node script.js

Christalchristalle answered 5/5, 2018 at 11:40 Comment(1)
node -r babel-register scripts.js works like charm and quite simple in devPersuader
H
6

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

Hansiain answered 25/1, 2016 at 21:6 Comment(4)
It has some warning regarding production use babeljs.io/docs/setup/#installation Not meant for production use The require hook is primarily recommended for simple cases.Calyx
in this case, how am I going to run my app in production? Do I need to compile my files down to es5? :/Varmint
@sandip_rb yes you must compile your files before going to production. you must figure out this solution works for node.js versions doesn't support ES6 (less than 4.x versions), Now node.js version support ES6Hansiain
@sandip_rb see useful link about use babel into production -> medium.com/@Cuadraman/…Hansiain
C
3

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

Cesaro answered 20/7, 2015 at 9:43 Comment(0)
T
3

npm init es6

It creates a package.json file with the "type": "module" setting.

Talyah answered 4/4, 2022 at 3:31 Comment(1)
The Active LTS version of Node (v16 at this time) and beyond have most ES6 features enabled by default. Setting type to module in package.json only enables the import/export syntax. This has the side effect of disabling require() and not setting certain globals like __dirname which may not always be desirable.Fumigator
C
1

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.

Cleliaclellan answered 26/12, 2015 at 15:58 Comment(0)
I
1

Refer this:

https://mcmap.net/q/127688/-quot-unexpected-token-import-quot-in-nodejs5-and-babel

or this boilerplate:

Boilerplate: node-es6

Inculpate answered 23/7, 2018 at 18:20 Comment(0)
P
0

Since most of the answers on this page don't work anymore, this is the latest way as of May 2023:

Step 1: Install the necessary packages

In your project directory, run the following command to install the required packages:

npm install --save-dev @babel/core @babel/cli @babel/preset-env

This will install Babel core, the command line interface, and the preset for compiling modern JavaScript code.

Step 2: Configure Babel

Create a file named `babel.config.json` in the root directory of your project and add the following contents to it:
{
  "presets": ["@babel/preset-env"]
}

This tells Babel to use the @babel/preset-env preset, which includes support for the latest JavaScript syntax.

Step 3: Update your `package.json` file

Open your package.json file and add the following script to the scripts section:
   "dev": "babel -w src -d lib | nodemon lib",

This is just an example and it can change based on your project structure. This script compiles your JavaScript files from the /src directory to the /lib directory, and then runs nodemon on the compiled files. Note that this script assumes that your main entry file is named index.js. A more general script would be:

"<script name>: "babel -w <code directory> -d <final/dist directory> | <other scripts for running the server>"
Pylle answered 24/5, 2023 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.