Node ES6 Support and creating a project with Babel

suggest change

Current Node implements ES2015. Check newer syntax at node.green. import is standard module syntax. It runs in a .mjs file or when package.json contains "type": "module", with no transpiler. Babel is for syntax this Node version does not run yet.

The steps below are the older Babel 6 setup (babel-preset-es2015 and babel-preset-stage-2). Those preset names are not the current @babel/preset-env packages. import comes from the es2015 preset here. It is not a stage-0 proposal.

create a new node project

mkdir my-es6-app
cd my-es6-app
npm init

Install babel the ES6 preset and stage-0

npm install --save-dev babel-preset-es2015 babel-preset-stage-2 babel-cli babel-register

Create a new file called server.js and add a basic HTTP server.

import http from 'http'

http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('Hello World\n')
}).listen(3000, '127.0.0.1')

console.log('Server running at http://127.0.0.1:3000/')

import http from 'http' is module syntax. node server.js rejects it until Babel rewrites the file, or until the file is real ESM.

Create .babelrc in the project root:

{
  "presets": ["es2015", "stage-2"],
  "plugins": []
}

Run this file with Babel 6's CLI:

npx babel-node server.js

Do not run the transpiler on every production request. Compile once, then run the output. These scripts match server.js in the project root:

"scripts": {
  "start": "node dist/server.js",
  "dev": "babel-node server.js",
  "build": "babel server.js --out-file dist/server.js",
  "postinstall": "npm run build"
}

npm install runs postinstall, which writes dist/server.js. npm start runs that file. npm run dev runs Babel in the development process.

To restart on file changes, npm install nodemon --save-dev and set the dev script to:

"dev": "nodemon server.js --exec babel-node"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents