In this article, we’re going to look at creating a build setup for handling modern JavaScript (running in web browsers) using Babel and Webpack.
This is needed to ensure that our modern JavaScript code in particular is made compatible with a wider range of browsers than it might otherwise be.
JavaScript, like most web-related technologies, is evolving all the time. In the good old days, we could drop a couple of <script>
tags into a page, maybe include jQuery and a couple of plugins, then be good to go.
However, since the introduction of ES6, things have got progressively more complicated. Browser support for newer language features is often patchy, and as JavaScript apps become more ambitious, developers are starting to use modules to organize their code. In turn, this means that if you’re writing modern JavaScript today, you’ll need to introduce a build step into your process.
As you can see from the links beneath, converting down from ES6 to ES5 dramatically increases the number of browsers that we can support.
The purpose of a build system is to automate the workflow needed to get our code ready for browsers and production. This may include steps such as transpiling code to a differing standard, compiling Sass to CSS, bundling files, minifying and compressing code, and many others. To ensure these are consistently repeatable, a build system is needed to initiate the steps in a known sequence from a single command.
Prerequisites
In order to follow along, you’ll need to have both Node.js and npm installed (they come packaged together). I would recommend using a version manager such as nvm to manage your Node installation (here’s how), and if you’d like some help getting to grips with npm, then check out SitePoint’s beginner-friendly npm tutorial.
Set Up
Create a root folder somewhere on your computer and navigate into it from your terminal/command line. This will be your <ROOT>
folder.
Create a package.json
file with this:
npm init -y
Note: The -y
flag creates the file with default settings, and means you don’t need to complete any of the usual details from the command line. They can be changed in your code editor later if you wish.
Within your <ROOT>
folder, make the directories src
, src/js
, and public
. The src/js
folder will be where we’ll put our unprocessed source code, and the public
folder will be where the transpiled code will end up.
Transpiling with Babel
To get ourselves going, we’re going to install babel-cli, which provides the ability to transpile ES6 into ES5, and babel-preset-env, which allows us to target specific browser versions with the transpiled code.
npm install babel-cli babel-preset-env --save-dev
You should now see the following in your package.json
:
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1"
}
Whilst we’re in the package.json
file, let’s change the scripts
section to read like this:
"scripts": {
"build": "babel src -d public"
},
This gives us the ability to call Babel via a script, rather than directly from the terminal every time. If you’d like to find out more about npm scripts and what they can do, check out this SitePoint tutorial.
Lastly, before we can test out whether Babel is doing its thing, we need to create a .babelrc
configuration file. This is what our babel-preset-env
package will refer to for its transpile parameters.
Create a new file in your <ROOT>
directory called .babelrc
and paste the following into it:
{
"presets": [
[
"env",
{
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}
]
]
}
This will set up Babel to transpile for the last two versions of each browser, plus Safari at v7 or higher. Other options are available depending on which browsers you need to support.
With that saved, we can now test things out with a sample JavaScript file that uses ES6. For the purposes of this article, I’ve modified a copy of leftpad to use ES6 syntax in a number of places: template literals, arrow functions, const and let.
"use strict";
function leftPad(str, len, ch) {
const cache = [
"",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
];
str = str + "";
len = len - str.length;
if (len <= 0) return str;
if (!ch && ch !== 0) ch = " ";
ch = ch + "";
if (ch === " " && len < 10)
return () => {
cache[len] + str;
};
let pad = "";
while (true) {
if (len & 1) pad += ch;
len >>= 1;
if (len) ch += ch;
else break;
}
return `${pad}${str}`;
}
Save this as src/js/leftpad.js
and from your terminal run the following:
npm run build
If all is as intended, in your public
folder you should now find a new file called js/leftpad.js
. If you open that up, you’ll find it no longer contains any ES6 syntax and looks like this:
"use strict";
function leftPad(str, len, ch) {
var cache = ["", " ", " ", " ", " ", " ", " ", " ", " ", " "];
str = str + "";
len = len - str.length;
if (len <= 0) return str;
if (!ch && ch !== 0) ch = " ";
ch = ch + "";
if (ch === " " && len < 10) return function () {
cache[len] + str;
};
var pad = "";
while (true) {
if (len & 1) pad += ch;
len >>= 1;
if (len) ch += ch;else break;
}
return "" + pad + str;
}
Continue reading %Setting up an ES6 Project Using Babel and webpack%
by Chris Perry via SitePoint
No comments:
Post a Comment