This document is translated from github.com/jamiebuilds… Examined by tufinch sauce.

This document covers everything you need to know about the use of Babel and its related tools.

directory

  • The introduction
  • Configure the Babel environment
    • babel-cli
    • Run the Babel CLI inside the project
    • babel-register
    • babel-node
    • babel-core
  • Configure the Babel
    • .babelrc
    • babel-preset-es2015
    • babel-preset-react
    • babel-preset-stage-x
  • Execute the code generated by Babel
    • babel-polyfill
    • babel-runtime
  • Configuring Babel (Advanced)
    • Manually specifying plug-ins
    • Plug-in options
    • Customize Babel based on the environment
    • Build your own Preset
  • Babel and other tools
    • Static analysis tool
    • Linting
    • The document
    • The framework
      • React

The introduction

Babel is a general-purpose compiler for JavaScript that enables you to use (or create) the next generation of JavaScript, as well as the next generation of JavaScript tools.

JavaScript as a language continues to evolve, bringing with it many new specifications and recommendations, and using Babel allows you to use these new specifications and recommendations before they become widely available.

Babel does what was mentioned in the previous paragraph by compiling the latest standard JavaScript code into code that already works today. This process is called “source-to-source” compilation, which is also known as “conversion”.

For example, Babel can take the arrow function syntax of the latest ES2015 from:

const square = n= > n * n;
Copy the code

Convert to the following:

const square = function square(n) {
  return n * n;
};
Copy the code

However, Babel can do more because it supports syntax extensions such as the JSX syntax for React or the Flow syntax for static type checking.

One step further, everything is a plug-in in Babel, and everyone can take advantage of Babel’s power to create their own plug-ins. Babel is organized into several core modules that allow users to build the next generation of JavaScript toolchains using these modules.

Many people are doing the same. Babel’s ecosystem is growing. In this Babel manual, I’ll explain some of the tools built into Babel and some of the tools that are available in the community.

Babel module

Because the JavaScript community has no standard build tools, frameworks, platforms, etc., Babel official is integrated with all the other major tools. Whether it’s from Gulp, Browserify, Ember, Meteor, or Webpack, whatever your startup tool, Babel has some official integration.

For the purposes of this manual, we’ll cover the built-in methods for setting up Babel, but you can also visit the interactive Settings page to see all the integrations.

Note: This guide will refer to command-line tools such as Node and NPM. You should be satisfied with these tools before proceeding with anything.

babel-cli 

The CLI of Babel is a simple way to compile files with Babel from the command line.

Let’s first install it globally to learn the basics.

$ npm install --global babel-cli
Copy the code

We can compile our first file like this:

$ babel my-file.js
Copy the code

This dumps the compiled output directly to your terminal. To write it to a file, we specify –out-file or -o.

$ babel example.js --out-file compiled.js
# or
$ babel example.js -o compiled.js
Copy the code

If we want to compile the entire directory into a new directory, we can do this using –out-dir or -d.

$ babel src --out-dir lib
# or
$ babel src -d lib
Copy the code

Run Babel CLI from the project

Although you can install Babel CLI globally on your computer, it is best to install it locally on a project-by-project basis.

There are two main reasons for this.

  • Different projects on the same computer may depend on different versions of Babel, allowing you to update one version at a time.
  • This means that you are not implicitly dependent on the environment in which you work. Make your project more portable and easy to set up.

We can install Babel CLI locally by running the following command:

$ npm install --save-dev babel-cli
Copy the code

Note: Since running Babel globally is usually a bad idea, you may need to uninstall the global copy by running the following command:

$ npm uninstall --global babel-cli
Copy the code

When the installation is complete, your package.json file should look like this:

{
  "name": "my-project"."version": "1.0.0"."devDependencies": {
    "babel-cli": "^ 6.0.0"}}Copy the code

Now, instead of running Babel directly from the command line, you can put commands into NPM scripts that use the local version. Simply add a “script” field to your package.json and put the Babel command into it to build.

{"name": "my-project", "version": "1.0.0",+ "scripts": {
+ "build": "babel src -d lib"
+},"DevDependencies ": {"babel-cli": "^6.0.0"}}Copy the code

Now, from our terminal we can run:

npm run build
Copy the code

This will run Babel in the same way as before, except now we are using a local copy.

babel-register 

The next most common way to run Babel is through babel-Register. With this option, you only need files to run Babel, which may be better integrated with your setup.

Please note that this is not for production use. Deploying code compiled in this way is considered bad practice. It is best to compile well in advance of deployment. However, this works great for build scripts or other things you run locally.

First let’s create an index.js file in our project.

console.log("Hello world!");
Copy the code

If we run it using Node index.js, Babel will not compile it. Therefore, we need to set up babel-Register first.

First, install babel-Register.

$ npm install --save-dev babel-register
Copy the code

Next, create a register.js file in your project and write the following code:

require("babel-register");
require("./index.js");
Copy the code

This registers Babel in Node’s module system and starts compiling each require file.

Now we can use node egister.js instead of running node index.js.

$ node register.js
Copy the code

Note: You cannot register Babel in the file to be compiled. Node is executing the file before Babel has a chance to compile it.

require("babel-register");

// not compiled:
console.log("Hello world!");
Copy the code

babel-node 

If you just run some code through the Node CLI, the easiest way to integrate Babel is probably to use the Babel-Node CLI, which is largely an alternative to the Node CLI.

Please note that this is not for production use. Deploying code compiled in this way is considered bad practice. It is best to compile well in advance of deployment. However, this works great for build scripts or other things you run locally.

First, make sure you have babel-CLI installed.

$ npm install --save-dev babel-cli
Copy the code

** Note: ** If you want to know why you want to install this software locally, read “Running Babel CLI from A Project” in the project section above.

Then, replace any location where node is running with babel-node.

If you are using NPM script, simply do the following:

  {
    "scripts": {
- "script-name": "node script.js"
+ "script-name": "babel-node script.js"}}Copy the code

Otherwise, you will need to write out the path to babel-Node itself.

- node script.js
+ ./node_modules/.bin/babel-node script.js
Copy the code

babel-core 

If for some reason you need to use Babel in your code, you can use the Babel-core package itself.

First, install babel-core.

$ npm install babel-core
Copy the code
var babel = require("babel-core");
Copy the code

If you have a JavaScript string, you can compile it directly using babel.transform.

babel.transform("code();", options);
// => { code, map, ast }
Copy the code

If files are used, the asynchronous API can be used:

babel.transformFile("filename.js", options, function(err, result) {
  result; // => { code, map, ast }
});
Copy the code

If you already have Babel AST for any reason, you can convert directly from the AST.

babel.transformFromAst(ast, code, options);
// => { code, map, ast }
Copy the code

Babeljs. IO /docs/usage/… .

Configure the Babel

You may have noticed by now that just running Babel doesn’t seem to do anything other than copy JavaScript files from one location to another.

That’s because we haven’t told Babel what to do.

Because Babel is a general-purpose compiler, it is used in many different ways, so by default it does nothing. You must tell Babel exactly what it should do.

You can provide instructions for Babel by installing **plugins ** or **presets ** (plugins group).

.babelrc 

Before we start telling Babel what to do. We need to create a configuration file. All you need to do is create a.babelrc file in the root directory of your project. Start like this:

{
  "presets": []."plugins": []}Copy the code

This file is how you configure Babel to perform the desired actions.

Note: While there are other ways you can pass options to Babel, the.babelrc file is the convention and the best way to do it.

babel-preset-es2015 

Let’s start by telling Babel to compile ES2015 (the latest version of the JavaScript standard, also known as ES6) into ES5 (the version available in most JavaScript environments today).

We will do this by installing the “ES2015” Babel default (of course, most of the ES2015 features are supported by the browser now, here is for demonstration, the use of the form is consistent) :

$ npm install --save-dev babel-preset-es2015
Copy the code

Next, we will modify.babelrc to include this preset.

  {
    "presets": [
+ "es2015"
    ],
    "plugins": []
  }
Copy the code

babel-preset-react 

Setting React is also easy. Simply install the preset:

$ npm install --save-dev babel-preset-react
Copy the code

Then add the preset to your.babelrc file:

  {
    "presets": [
      "es2015",
+ "react"
    ],
    "plugins": []
  }
Copy the code

babel-preset-stage-x 

JavaScript also makes recommendations that are being incorporated into the standard through the TC39 (technical committee behind the ECMAScript standard) process.

This process is divided into five stages (0-4). As proposals gained greater traction and were more likely to be adopted as standards, they went through various stages, culminating in phase 4 acceptance as a standard.

These are bundled into four different presets in the form of Babel:

  • babel-preset-stage-0 
  • babel-preset-stage-1 
  • babel-preset-stage-2 
  • babel-preset-stage-3 

Note that there is no preset for stage 4 as it is only the ES2015 preset above.

Each of these presets is required for subsequent phases. That is, babel-preset-stage-1 requires babel-preset-stage-2, and babel-preset-stage-3 is also required.

Installing the stages you are interested in is simple:

$ npm install --save-dev babel-preset-stage-2
Copy the code

You can then add it to your.babelrc configuration.

  {
    "presets": [
      "es2015",
      "react",
+ "stage-2"
    ],
    "plugins": []
  }
Copy the code

Execute the code generated by Babel

So far, you’ve compiled code using Babel, but that’s not the end of the story.

babel-polyfill 

Almost all future JavaScript syntax can be compiled using Babel, but the API is not.

For example, the following code has arrow function functionality to compile:

function addAll() {
  return Array.from(arguments).reduce((a, b) = > a + b);
}
Copy the code

After compiling, it will look like this:

function addAll() {
  return Array.from(arguments).reduce(function(a, b) {
    return a + b;
  });
}
Copy the code

However, since array. from does not exist in every JavaScript environment, it remains unusable after compilation:

Uncaught TypeError: Array.from is not a function
Copy the code

To solve this problem, we use something called Polyfill. In short, Polyfill is a piece of code that copies an API that doesn’t exist in the current runtime, allowing you to use apis like Array.from ahead of time before the current environment becomes available.

Babel uses the excellent Core-JS for its polyfill, as well as a custom ReGenerator runtime to make generators and asynchronous functions work.

To include Babel Polyfill, first install it using NPM:

$ npm install --save babel-polyfill
Copy the code

Then simply include polyfill at the top of any file that needs it:

import "babel-polyfill";
Copy the code

babel-runtime 

To implement the ECMAScript specification details, Babel uses “helper” methods to keep the generated code clean.

Because these “Helper” methods get long and are added to the top of every file, you can move them into a single “runtime” of require.

Install babel-plugin-transform-runtime and babel-runtime:

$ npm install --save-dev babel-plugin-transform-runtime
$ npm install --save babel-runtime
Copy the code

Then update your.babelrc:

  {
    "plugins": [
+ "transform-runtime",
      "transform-es2015-classes"
    ]
  }
Copy the code

Now, Babel will code like this:

class Foo {
  method(){}}Copy the code

Compile like this:

import _classCallCheck from "babel-runtime/helpers/classCallCheck";
import _createClass from "babel-runtime/helpers/createClass";

let Foo = function () {
  function Foo() {
    _classCallCheck(this, Foo);
  }

  _createClass(Foo, [{
    key: "method".value: function method() {}}]);returnFoo; } ();Copy the code

Instead of putting the _classCallCheck and _createClass helper functions in every file you need.

Configuring Babel (Advanced)

Most people can use Babel by using only the built-in presets, but Babel is much more than that.

Manually specifying plug-ins

The Babel default is simply a collection of preconfigured plug-ins that you can specify manually if you want to do something different. This is almost identical to the preset.

Start by installing a plug-in:

$ npm install --save-dev babel-plugin-transform-es2015-classes
Copy the code

Then add the plugins field to your.babelrc.

  {
+ "plugins": [
+ "transform-es2015-classes"
+]
  }
Copy the code

This gives you more precise control over the exact transforms that are being run.

For a complete list of official plug-ins, see the Babel Plug-ins page.

Also take a look at all the plug-ins the community has built. If you want to learn how to write your own plug-in, read the Babel Plug-in manual (the Tuq community will translate this plug-in manual later, so stay tuned!).

Plug-in options

Many plug-ins also have options to configure them for different behaviors. For example, many Transforms have loose mode, which abandons some canonical behavior in favor of simpler, higher-performance code.

To add options to the plug-in, simply make the following changes:

  {
    "plugins": [
- "transform-es2015-classes"
+ ["transform-es2015-classes", { "loose": true }]]}Copy the code

Customize Babel to your environment

The Babel plug-in solves many different tasks. Many of these are development tools that help you debug your code or integrate with the tools. There are also many plug-ins for optimizing code in production.

Therefore, context-based Babel configuration is usually required. You can do this easily using the.babelrc file.

  {
    "presets": ["es2015"],
    "plugins": [],
+ "env": {
+ "development": {
+ "plugins": [...]
+},
+ "production": {
+ "plugins": [...]
+}}}Copy the code

Babel will enable configuration within env based on the current environment.

The current environment will use process.env.babel_env. When BABEL_ENV is not available, it falls back to NODE_ENV, and if not, defaults to “development”.

Unix

$ BABEL_ENV=production [COMMAND]
$ NODE_ENV=production [COMMAND]
Copy the code

Windows

$ SET BABEL_ENV=production
$ [COMMAND]
Copy the code

Note: [COMMAND] is whatever you use to run Babel (that is, Babel, babel-node, or maybe just Node if you’re using the babel-Register hook).

Tip: If you want commands to run cross-platform on Unix and Windows, use cross-env.

Build your own presets

Manually specify plug-ins? Plug-in options? Context-based Settings? All of these configurations seem to be repeated many times for all projects.

Therefore, we encourage the community to create their own presets. This can be the default for your entire company.

Creating presets is easy. Suppose you have the following.babelrc file:

{
  "presets": [
    "es2015"."react"]."plugins": [
    "transform-flow-strip-types"]}Copy the code

All you need to do is create a new project according to the naming convention babel-preset-* (please be responsible for this namespace!). And create two files.

First, create a new package.json file with the dependencies relationship your default requires.

{
  "name": "babel-preset-my-awesome-preset"."version": "1.0.0"."author": "James Kyle <[email protected]>"."dependencies": {
    "babel-preset-es2015": "^ 6.3.13"."babel-preset-react": "^ 6.3.13"."babel-plugin-transform-flow-strip-types": "^ 6.3.15"}}Copy the code

Then create an index.js file that exports the contents of the.babelrc file and replaces the plug-in/default string with the require call.

module.exports = {
  presets: [
    require("babel-preset-es2015"),
    require("babel-preset-react")].plugins: [
    require("babel-plugin-transform-flow-strip-types")]};Copy the code

Then simply publish it to NPM and you can use it like any preset.

Babel combines with other tools

Babel is straightforward to set up once you’ve mastered it, but it can be very difficult to set up with other tools. However, we try to work closely with other projects to make the experience as easy as possible.

Static analysis tool

Newer standards bring a lot of new syntax to the language, and static analysis tools are just beginning to take advantage of it.

Linting

ESLint is one of the most popular Lint tools, so we maintain the official Babel-ESLint integration. Install ESLint and babel-esLint first.

$ npm install --save-dev eslint babel-eslint
Copy the code

Next, create or use an existing.eslintrc file in your project and set the parser to babel-eslint.

  {
+ "parser": "babel-eslint","rules": { ... }}Copy the code

Now add a Lint task to your NPM package.json script:

  {
    "name": "my-module",
    "scripts": {
+ "lint": "eslint my-files.js"
    },
    "devDependencies": {
      "babel-eslint": "...",
      "eslint": "..."
    }
  }
Copy the code

Then simply run the task to complete the setup.

$ npm run lint
Copy the code

Refer to the babel-ESLint or ESLint documentation for more information.

The document

With Babel, ES2015, and Flow, you can infer a lot about your code. With document.js, you can easily generate detailed API documentation.

Documentation. Js uses Babel behind the scenes to support all the latest syntax, including Flow annotations, for declaring types in code.

The framework

Right now, all the major JavaScript frameworks are focused on tailoring their apis around the future of the language. So, a lot of work goes into the tool.

The framework has the opportunity not only to use Babel, but to extend it in ways that improve the user experience.

React

React has dramatically changed its API to make it consistent with ES2015 classes (read about the updated API here). Further, React relies on Babel to compile its JSX syntax and disapproves of Babel using its own custom tools. You can follow the instructions above to start setting up the babel-preth-React package.

The React community accepted Babel and worked with it. The community is now undergoing many transformations.

The most famous is the babel-plugin-React-Transform plug-in, which combines a number of React-specific transformations to enable hot module reinstalls and other debugging utilities.