Compile weback JS
Objective: To convert ES6+ to ES5, thus ensuring JS compatibility in older browsers
The solution
I. Babel /preset-env(some advanced grammars cannot be converted like promise)
Let’s take a quick look at Babel
Let’s translate the following ES6 code into ES5
Install dependencies
yarn add babel-loader @babel/core @babel/preset-env
Copy the code
webpack.config.js
const { resolve } = require('path');
const MiniCssEctractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode:'development',
entry: './src/index.js',
output: {
path: resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module:{
rules:[
{
test: /.css$/i,
use:[MiniCssEctractPlugin.loader,'css-loader']
},{
test: /.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { targets: "defaults" }]
]
}
}
}
]
},
plugins:[
new MiniCssEctractPlugin({
filename:'css/[name].css'
}),
new HtmlWebpackPlugin({
template:'src/index.html'
})
]
}
Copy the code
The output
As you can see, some basic ES6 conversions work, but promises and the like do not. Check the source code and find that promises are not translated.
2. Babel /polyfill(translate all new JS syntax)
Yarn add @babel/polyfill -d import '@babel/polyfill' // import from the import fileCopy the code
When we look at the source code at this time, it has been translated into ES5. Open it again with IE and find it still doesn’t work. What’s the problem? You also need to add build target environment
// webpack.conf.js
module.export = {
// ...
target: ["web", "es5"]
}
Copy the code
However, we found that there was another problem. The packaged code became very large because it would convert ES6 and ES6+ code to ES5.
3, Core-JS (on-demand translation of JS new syntax)
You need to comment out the polyfill that you introduced earlier
yarn add core-js -D
Copy the code
Configuration:
On demand: useBuildIns:'usage' Specifies version: corejs:3Copy the code
const { resolve } = require('path');
const MiniCssEctractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode:'development',
entry: './src/index.js',
output: {
path: resolve(__dirname, 'dist'),
filename: 'mian.js'
},
module:{
rules:[
{
test: /.css$/i,
use:[MiniCssEctractPlugin.loader,'css-loader']
},{
test: /.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env',
{
useBuiltIns: 'usage',
corejs: 3,
targets: {
chrome: '58',
ie: '9',
firefox: '60',
safari: '10',
edge: '17'
}
}]
]
}
}
}
]
},
plugins:[
new MiniCssEctractPlugin({
filename:'css/[name].css'
}),
new HtmlWebpackPlugin({
template:'src/index.html'
})
],
target:["web","es5"]
}
Copy the code
And then if you look at the volume, it’s a lot smaller.