This is an extremely exciting time to be a JavaScript developer. The language is growing and changing in very positive ways. But, unfortunately, many of the best features of modern JavaScript are not natively available in Node or the browsers. I, along with others, say that it is absolutely essential that we begin writing using the new syntax now rather than waiting for some hopeful future where it is natively implemented universally. But, many would now ask an important question...
Why should we use the new syntax?
First, JavaScript has been considered for a long time to be an "ugly" language, overly verbose and full of punctuation. The new syntax allows us to write much more concise and good-looking code, and even encourages better practices.
Second, many libraries (React, for instance) are now being implemented using the new syntax, and the documentation you find online these days is increasingly written using the new features and syntax. If your build process can't handle the new syntax, then you won't be able to follow the documentation without investing extra time and energy into re-implementing what you are reading into the old syntax.
Third, it is the future. This is the most simple reason. If you want to be a JavaScript developer from a few years ago, feel free to ignore the latest features and syntax. If you still want to be a JavaScript developer a few years from now, then today is the day to take the dive.
Fourth, it is easy to begin using this syntax today. There is nothing complicated about it. You just add a build step and begin writing whatever kind of JavaScript you want.
So, now, having briefly made my case, let me show you how to configure your Node project to use ES2015/2016.
Step #1 Install Babel
From your terminal, and in your project directory, enter:
npm install babel-cli --save-dev
This will install Babel. But notice how we used the flag --save-dev
rather than just save
as in my previous posts. The save-dev
flag tells npm to record the package in your package.json
file, but rather than save it under dependencies
, it saves it under devDependencies
. These are dependencies which are used in development, but npm knows are not needed in production.
Now, since we have Babel installed, let's install the preset for ES2015 syntax:
npm install babel-preset-es2015 --save-dev
You can use presets and plugins to get Babel to do exactly what you need it to do. In this case, we want to be able to write our code and have it outputted as universally-compatible ES5 code. This preset tells Babel what it needs to know in order to do that.
But, before Babel will actually transpile our code, we need to create a config file which will tell Babel to use that preset. So, create a file named .babelrc
in the root of your project directory and enter the following into it:
{
"sourceMap": false,
"presets": [
"es2015"
],
"plugins": []
}
In another blog post we will talk about adding plugins, but for now we just need Babel to know that we want it to use the preset es2015
.
Step #2 Create a src
and a lib
directory
As you might imagine, your source files will live in your src
directory and your transpiled code will live in your lib
directory. So, go ahead and create both of those folders in the root of your project folder. If you already have an index.js
file, go ahead and move that into the src
directory and rename it to main.js
. If not, then just create a file named main.js
in the src
directory.
Step #3 Write Some Code!
In lib/main.js
go ahead and write some ES2015 code:
// This is written using ES5 syntax
var hello1 = function(name) {
return 'Hellooooo... ' + name + '.';
};
// This is written using ES2015 syntax
var hello2 = (name) => `Hellooooo... ${name}.`;
console.log(hello1('Oldman'));
console.log(hello2('Newman'));
Step #4 Add Your Build Scripts
Open up your package.json
file. Remove any scripts currently listed there and add the following:
{
...
{
"start": "node lib/main.js",
"build": "babel src --out-dir lib",
"watch": "babel src --watch --out-dir lib"
}
...
}
The start
script is what you will use to start your application. The build
script will take all of your code in the src
directory, convert it to ES5, and place the new files in the lib
directory. The watch
script will have Babel watch the src
folder and automatically recompile as you change files.
Step #5 Compile Your Code!
From your project directory, enter:
npm run build
Now, if all went well, you should find a fancy new main.js
file in your lib
directory. Go ahead and open that up. It should look something like the following:
'use strict';
var hello1 = function hello1(name) {
return 'Hellooooo... ' + name + '.';
};
var hello2 = function hello2(name) {
return 'Hellooooo... ' + name + '.';
};
console.log(hello1('Oldman'));
console.log(hello2('Newman'));
Notice how the arrow function I used in the original hello2
function was replaced by Babel with a traditional function declaration. Also, notice the returned template string was replaced with traditional strings using +
to concatenate.
Now, from back in your terminal, enter npm start
and you will see the output of your application.
So, I hope you can see now how this works. You can write in old ES5 code or ES2015! It's up to you. If you are following a tutorial or reading docs written in ES2015, it's no problem for you to follow along in your own application. Or, if you are following an older tutorial, that's no problem either. Your build process can now handle whatever JavaScript you write!
Step #6 Build a Module
One of the best features of ES2015 is its modules system. From here on out, you should always try and write your modules using ES2015. But, before we make some modules, let's get Babel watching our src directory for changes. From your teminal, enter:
npm run watch
Create a folder named modules
inside your src
folder. Inside that folder, create a file named adder.js
. Open up that file and enter the following:
const adder = (num1, num2) => num1 + num2;
export default adder;
As you can see, I declared a constant named adder
and made it a function which adds two numbers together. Then I exported adder
as the default export. There are other ways to export than using default, but default is easiest and does the trick here.
Now, let's make some use of that module. Open up src/main.js
and replace its contents with the following:
import adder from './modules/adder';
const num1 = 4;
const num2 = 5;
const sum = adder(num1, num2);
console.log(`The sum of ${num1} and ${num2} is ${sum}`);
So, I imported the default export of my adder
module into a variable named adder
. ES2015
module importing and exporting are more clear and straightforward that older CommonJS packages (in my humble opinion). It is as easy as export default something
and import something from 'path'
.
Conclusion
You are now set! You could create a whole application just with what you know now. You can install npm dependencies and import them (e.g. import colors from 'colors'
) and you can create your own modules. You can write in ES5 or ES2015, whichever you like!
In my next post, I will show you how to install and configure Mocha for testing your modules.
Further Reading:
- For a brief introduction to ES2015 syntax and features check this out: http://babeljs.io/docs/learn-es2015/
- For a more in-depth look at ES2015, check out the extremely well-written book, "Exploring ES6" by Axel Rauschmayer https://leanpub.com/exploring-es6
This is part four of an ongoing series:
- First Time Node - #1 Getting Started
- First Time Node - #2 Packages
- First Time Node - #3 Setting Up Your Development Environment
- First Time Node - #4 Configuring Your Build Process for ES2015/2016
- First Time Node - #5 Configuring & Writing Tests
- First Time Node - #6 Express Server With Functional Views