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.
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
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