Node.js: Use Babel to run ES6 JavaScript
Last updated: 26th July 2020It's quick to try out ES6 style code in JavaScript. In your terminal:
npm install -g babel
Create a new file sum.js
:
const sum = arr => arr.reduce((a, b) => a + b);
console.log( 'sum: ', sum([1,2,3]) )
Then run this command in your terminal:
babel-node sum.js
You can even run babel-node
without any arguments and use the REPL to execute JS on the fly. If you introduce it into a project, there are babel packages for Gulp and Grunt.
Update July 2020
Newer versions of Node.js support this syntax out of the box, and even if it doesn't, you may still be able to pass flags to experiment with such features. For example to try top-level await:
node --experimental-repl-await
Which lets you type the following in the Node.js REPL:
> await Promise.resolve(1) // 1
Extra
When running, for example, Node.js code, you've probably experiences long stack traces which aren't very useful. Here's a tip on how to create pretty looking stack traces, where you can easily see the exact line of code which threw an error.