Why convert ES6 to ES5 code?

The short answer is: for browser compatibility and for running applications smoothly in node.js.

Older browsers do not support ES6 syntax, so you need to switch to the more compatible ES5.

In node.js, Node support for ES6 has been criticized, and module mode was introduced after version 13 (“type”: “module” was added to package.json), but some libraries still don’t support ES6 syntax. So, if your Node.js program does not know ES6 syntax, use Babel transcoding to solve the problem.

What’s a Babel?

In a nutshell, Babel is a translation tool. Originally posted on Reddit in 2014 as an obscure side project, it has evolved into a fundamental tool for Node.js app development.

How do I use Babel

Let’s write out the process of using Babel at the command line to give you a sense of what the translation process is all about.

1. Install command line tools for Babel in the project

npm install -D babel-cli
Copy the code

2. Prepare the ES6 code

Usually we put the source code in the SRC directory. If you don’t have any existing ES6 code, create one in the SRC directory:

// src/example.js class Hello { static world() { console.log('Hello, World! '); } } Hello.world();Copy the code

3. The configuration of Babel

Babel is used to translate code via plug-ins and preset (so it can be preset to more than ES6). To translate ES6 to ES5, we just need to configure the env default and install this plugin:

npm install -D babel-preset-env
Copy the code

We also need a configuration file. In the project root directory, create a file:.babelrc with the following contents:

// .babelrc
{
  "presets": ["env"]
}
Copy the code

4. Create the NPM command

This step is not necessary because it is already configured. You can simply run the following command:

babel src -d build
Copy the code

This translates the Javascript code in the SRC directory into ES5 and stores it in the build directory.

Traditionally, we put the door-to-door command in the NPM command. In your project’s package.json, enter the following:

"scripts": {
  "build": "babel src -d build",
},
Copy the code

You can then use the following command to translate ES6 code:

npm run build
Copy the code