Skip to content

Instantly share code, notes, and snippets.

@paulcuth
Last active October 5, 2016 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulcuth/1c13b93c30794cdbd2f956b02fafbd30 to your computer and use it in GitHub Desktop.
Save paulcuth/1c13b93c30794cdbd2f956b02fafbd30 to your computer and use it in GitHub Desktop.

Running ES6 in Node

The latest versions of Node do support most of the ES6 syntax. However, notably, they still do not support import and export expressions. In order to use these espressions we can turn to Babel.

Babel provides a wrapper around Node that automatically translates a given source file before running it in the normal Node application installed on your machine. This wrapper application is called babel-node and is provided in the babel-cli package.

However, import and export translators are not in the core Babel functionality, we'll need to add a preset. The translators needed here are in the es2015 Babel preset.

Quick version

Installing Babel CLI globally enables you to use the babel-node command to run your app in terminal (remember to replace src/app.js with the path to your entry point):

npm install -g babel-cli babel-preset-es2015
babel-node src/app.js --presets es2015

Easier-to-type version

It can be cumbersome to type babel-node src/app.js --presets es2015 every time you run your app, so let's add it to our NPM scripts instead.

NPM scripts do not work with globally installed applications/packages, so we need to install our dependencies again, but locally to the project this time.

npm install babel-cli babel-preset-es2015 --save-dev

Now we can create the script; add the following to the scripts section of package.json (again, remember to replace ./src/app.js with the path to your entry point):

  "scripts": {
    //...
    "start": "babel-node ./src/app.js --presets es2015",
  }

And finally, run it.

npm start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment