1. Preface
Because the ES6 syntax is supported on various browsers, some browsers have a high degree of support for ES6 syntax, and some browsers support low, so in order to be compatible with most browsers, we need to use the Babel compiler to compile the ES6 syntax in the code into ES5 syntax when using ES6 syntax. Below, we start to build a Webpack+babel-based ES6 syntax runtime environment.
2. Packages that need to be installed
Before setting up the environment we need to install the following JS package:
- Webpack (Installation Webpack, must install)
- Babel-loader and Babel-core (Babel transcoding device, must be installed)
- BABEL-PRESET-ES2015 (transcoding rules, transcoding by es2015 rules, must be installed)
- Webpack-dev-server (Browser hot update use, optional)
You can install it quickly using one of the following commands:
CNPM Install Babel-loader babel-core babel-preset-es2015 webpack webpack-dev-server--save-dev
3. New Project
After installing the required packages, we can create a new code project to write the code, with the following directory structure as an example:
D:\ES6-ENV
│.babelrc
│index.html
│package.json
│webpack.config.js
├─dist
├─node_modules
└─src
└─main.js
Directory Structure Description
1.es6-env: Project folder
Configuration file for 2..babelrc:babel
3.index.html: Visited pages
4.webpack.config.js:webpack configuration file
5.dist:webpack the packaged output file
6.src/main.js: Writing ES6 code files
3.1 Babel configuration file. Babel
{ "presets": [ "es2015" ], "Plugins": []}
3.2 Webpack configuration file Webpack.config.js
varPath = require (' path '); Module.exports={//Entry FileEntry: './src/main.js ',//Export Documents output:{
FileName:' Bundle.js ',//Export File namePath:path.resolve (__dirname, ' dist ')//Export File path }, module:{rules:[{test:/\.js$/, use:[{loader:' Babel-loader '}], exclude: [//exclude Node_modules. js files that are not converted to the followingPath.resolve (__dirname, ' node_modules '))]}]}}
3.3 Package.json
{ "name": "Es6-env" , "version": " 1.0.0 " "description": " "main": " Index.js " "scripts" : { "dev": " Webpack-dev-server--port 8080--inline--hot--open "}, " keywords ": [], " author ":" , "license": "ISC" "devdependencies" : { "Babel-core": "^6.26.0" "Babel-loader": "^7.1.2" "babel-preset-es2015": "^6.24.1" Span style= "COLOR: #000000", "Webpack": "^3.10.0" "Webpack-dev-server" : "^2.11.0" }}
4. Playing the Code
After the configuration of the above environment, we can in the Src/main.js file crazy code, at this time the written ES6 grammar in the project after the operation can be correctly compiled into ES5 grammar!!!
Enter the following command at the command line to run the written code:
NPM Run Dev
Build ES6 syntax Runtime environment using Webpack+babel