项目目录:
QQ截图20200427160738.png
//webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2,
// localsConvention: '[name]--[local]--[hash:base64:5]',
sourceMap: true,
modules: true
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [['@babel/preset-env', {//注意这里是一个map结构
"modules": false,
"useBuiltIns": "usage",//按需加载转换语法
"corejs": 2//使用useBuiltIns字段必须声明@babel/runtime版本
}]],
//plugins: ['@babel/plugin-transform-runtime']
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin()
]
}
真正其起作用的就是这么一段:
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [[
'@babel/preset-env',//管你是2015还是2015,包含所有的ES版本
{
"modules": false,
"useBuiltIns": "usage",//polyfill按需引入
"corejs": 2//使用了useBuiltIns必须指定@babel/runtime版本
}
]],
// plugins: ['@babel/plugin-transform-runtime']
}
}
]
}
需要安装的依赖
{
"name": "my-loader",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/polyfill": "^7.8.7",
"@babel/preset-env": "^7.9.5",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.2.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
}
}
//index.js
const set = new Set()
new Promise((resolve, reject) => {
console.log(666);
resolve(123)
})
// console.log(123)
用IE11打开index.html
QQ截图20200427160931.png
从babel7.4开始,一些新的特性开始加入,可以这样使用
//webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode:"development",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [[
'@babel/preset-env',
{
"modules": false,
"useBuiltIns": "usage",
"corejs": 3
}
]],
plugins: [
['@babel/plugin-transform-runtime', {
"corejs": 3
}]
]
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin()
]
}
依赖包:
{
"name": "my-loader",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/plugin-transform-runtime": "^7.9.0",
"@babel/polyfill": "^7.8.7",
"@babel/preset-env": "^7.9.5",
"@babel/runtime-corejs3": "^7.9.2",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.2.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
}
}
主要就是使用了@babel/runtime-corejs3,但是发现这种方式打包后的体积增加了不少(难道是新特性引入的?),大家可以根据实际情况选择。