Reason: For browser compatibility and to run the application smoothly in the node.js environment. As a new specification for JS, ES6 adds a lot of new syntax and API, but modern browsers do not have high support for the new features of ES6, so it is necessary to convert ES6 code to ES5 code; you only need to install and configure the Babel tool in the project That’s it.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Why convert es6 to es5?
The simple answer is: for browser compatibility, and for the smooth running of applications in the node.js environment.
As a new specification for JS, ES6 adds a lot of new syntax and API. However, not all browsers on the market are compatible, so it is necessary to convert the ES6 syntax code into ES5 code.
Modern browsers do not have high support for the new features of ES6, so if you want to use the new features of ES6 directly in the browser, you have to use other tools.
In the node.js environment, node's support for ES6 has been criticized. It was only after version 13 that the module mode was introduced (add a sentence: "type": "module" to package.json). But some libraries still don't support ES6 syntax. Therefore, if your node.js program does not recognize ES6 syntax, please use Babel to transcode it, which may solve the problem.
How to convert es6 to es5?
Use babel to convert es6 to es5.
Below we write out the process of using Babel on the command line so that you can understand the entire translation process.
1. Install Babel’s command line tool in the project
npm install -D babel-cli
2. Prepare ES6 code
Usually we The source code is placed in the src directory. If you do not have ready-made ES6 code, create one in the src directory:
// src/example.js class Hello { static world() { console.log('Hello, World!'); } } Hello.world();
3. Configure Babel
Babel Yes Transpiles code via plugins and presets (so it can transpile more than just ES6). In order to translate ES6 to ES5, we only need to configure the env default value and install this plug-in:
npm install -D babel-preset-env
We also need a configuration file, create a file in the project root directory: .babelrc, the content is as follows:
// .babelrc { "presets": ["env"] }
4. Create npm command
This step is not necessary, because it has been configured before, you can directly execute the command:
babel src -d build
This will translate the Javascript code in the src directory into ES5 and store it in the build directory.
Conventionally, we put the door-to-door commands in the npm command. In the project's package.json, enter the following content:
"scripts": { "build": "babel src -d build", },
So you can use the following command to translate ES6 code:
npm run build
[Related recommendations:javascript video tutorial、web front end】
The above is the detailed content of Why convert es6 to es5. For more information, please follow other related articles on the PHP Chinese website!