Building Enterprise JavaScript Applications
上QQ阅读APP看书,第一时间看更新

Transpiling ES6 with Babel

We've been using the CommonJS require syntax for modules; let's change it to use the ES6 module syntax (using import).

In your code, update the first line to use import:

const http = require('http'); // CommonJS syntax
import http from 'http'; // ES6 syntax

When we try to run our server by executing node index.js, it will throw a SyntaxError: Unexpected token import error. This is because Node.js support for modules is still experimental, and not likely to be supported without the --experimental-modules flag until late 2018.

This means that for us to write our source code using ES6 modules, we need to add an extra step that will transpile the unsupported syntax into supported syntax. There are a few compilers/transpilers available for us to choose from:

  • Babel: The most popular and de facto standard for JavaScript compilers/transpilers.
  • Traceur: Another compiler by Google.
  • The TypeScript compiler: TypeScript is a superset of JavaScript that provides static typing. Since valid JavaScript is also valid TypeScript, the TypeScript compiler can also act as an ES6 to ES5 transpiler.
  • The Closure compiler: A compiler that optimizes your JavaScript by parsing and analyzing it, removing dead code, refactoring existing code, and minimizing the final results. It also warns the user of common mistakes. The Closure compiler supports the ES6 syntax, but transpiles everything down to ES5.

Whilst the TypeScript and Closure compilers are able to transpile ES6 to ES5, it is not their primary function; thus naturally, these features are of limited use here. Babel and Traceur are tools whose sole purpose is to transform the ES6/7/8/9 and ESNext syntax to JavaScript that is supported by the environment, and so would be more suitable for our use. Of the two, Babel is, by far, the most popular and active, and will be the one we use in this project.

ESNext is a collective term for features that have been submitted by members of the community, but have not gone through Ecma's review process (the T39 Process), and thus have not been incorporated into the ECMAScript standard.

There are 5 stages to the T39 Process: Strawman (Stage 0), Proposal (Stage 1), Draft (Stage 2), Candidate (Stage 3), and Finished (Stage 4). You can get a more detailed description of each stage by going to  https://tc39.github.io/process-document/.