Babel brief introduction and function
Babel is a JavaScript editor designed to convert ECMAScript 2015+ code into backwards-compatible JavaScript syntax, To be able to run in current and older browsers (Chrome, Safire, Firefox, IE) or other environments.
Project application
Plug-ins to install
- Babel – loader (must)
- @ Babel/croe (must)
npm i babel-loader @babel/croe -D
Copy the code
- @babel/preset-env(required): Basic JS compatibility processing, problem: only basic syntax can be converted, such as promise advanced syntax cannot
npm i @babel/preset-env -D
Copy the code
- Babel /polyfill: all JS compatibility processing, problem: as long as part of the compatibility problem is solved, all the compatibility code will be introduced, the volume is too large
npm i @babel/polyfill -D
Copy the code
- Core-js: load on demand if compatibility is required
npm i core-js -D
Copy the code
usage
Based on the above, it’s optimal to use @babel/ Preset -env with core-js to load compatibility code on demand
Webpack.config.js code configuration
const { resolve } = require('path'); const HtmlWebPackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: Resolve (__dirname, 'dist')}, module:{rules: [/* js Babel-loader @babel/ core@babel /preset-env 2. All js compatibility processing --> @babel/polyfill can be directly introduced in js files. */ {test: /\.js$/, exclude: / {test: /\.js$/, exclude: // node_modules/, loader: 'babel-loader', options: {// default: indicates what Babel does with presets: [['@babel/preset-env', {// Load useBuiltIns: 'usage', corejs:{version: 3}, // Specify which version of browser targets:{chrome: '60', firefox: '60', ie: '9', safari: '10', edge: '17' } } ] ] } } ] }, plugins: [ new HtmlWebPackPlugin({ template: './src/index.html' }) ], mode: 'development' }Copy the code
Compression JS
To compress JS, change the mode in webpack.config.js to production mode
mode: 'production
Copy the code
Compressed HTML
Modify the HtmlWebPackPlugin configuration in plugins in webpack.config.js
Plugins: [new HtmlWebPackPlugin({template: './ SRC /index.html', // collapse HTML code minify: {// Delete the space collapseWhitespace: True, // remove comment removeComments: true}})],Copy the code
The demo address
Reference video: B station is still silicon Valley