I will get straight to the point. ES6 is awesome and we want to use it in our Node.js project. We would use Babel to convert ES6 codes to ES5 compatible Javascript for Node. We first install Babel.
1 |
npm i babel -S |
Now we write our awesome app in ES6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Filename: main.es6 import express from "express" var app = express(); app.get("/", (req, res) => { res.json({hello: 'world'}); }); var port = process.env.PORT || 3000; var server = app.listen(port, () => { console.log('Service started on port :' + port); }); |
We could use Babel to transpile ES6 to ES5 and then run the ES5 code in Node. But instead we shall directly run ES6 with the “babel-node” binary. The babel-node binary transpiles ES6 code in runtime. So we don’t need any watchers or manual transpilation.
We modify our package.json’s script’s section to add the babel-node binary:
1 2 3 |
"scripts": { "start": "./node_modules/.bin/babel-node main.es6" } |
Now if we push to Heroku, it will work fine 🙂
5 replies on “ES6 on Node.js (And Heroku)”
For me I needed to use
babel-node.js
rather than simplybabel-node
, e.g."start": "./node_modules/babel/bin/babel-node.js index"
Fyi, babel-node is not recommended for production:Â https://babeljs.io/docs/usage/cli/
Hi, thanks for pointing it out. It was just a proof of concept. I am sure people would transpile the codes before pushing to production.
Does this still work? I got an error that says I need to use babel-cli.
Sorry this would no longer work. Please check the other blog post on async/await which demonstrates the newer way of doing things.