webpack中的require.ensure()可以实现按需加载资源包括js,css等,它会给里面require的文件单独打包,不和主文件打包在一起,webpack会自动配置名字,如0.js,1.js,但是这样看着不是很直观,所以要自己配置单独打包的chunk名字,好吧开始踩坑。
目录结构:
npm init -y
package.json代码:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
}
运行:
npm install
./src/index.html代码
Title click me
webpack.config.js代码
const path = require('path');
let HtmlwebpackPlugin = require('html-webpack-plugin');
let webpack=require('webpack');
module.exports = {
entry: "./src/index.js",
output: {
filename: "js/main.js",
path:path.resolve(__dirname,"./dist"),
publicPath:"/",
chunkFilename:'js/[name].js'
},
devServer: {
historyApiFallback: true,
inline: true
},
plugins: [
new HtmlwebpackPlugin({
title: 'Hello World app',
template: './src/index.html'
}),
new webpack.HotModuleReplacementPlugin()
]
};
index.js代码:
let btn = document.getElementById('mybun');
btn.addEventListener('click',function() {
require.ensure([], function() {
let a = require('./a.js');
/*import('./a.js')*/
},"oth");
},false);
a.js代码:
console.log('这是 a.js 里的内容')
require.ensure([], function() {
let a = require('./a.js');
/*import('./a.js')*/
},"oth")
require.ensure()里有三个参数,第一个参数是个数组,表明其第二个参数函数里需要依赖的模块,这些会提前加载;第二个是回调函数,在这个回调函数里面require的文件会被单独打包成一个chunk,不会和主文件打包在一起,这样就生成了两个chunk,第一次加载时只加载主文件,当点击时就会加载单独打包的chunk。第三个参数是单独打包的chunk的文件名。
要想自己设置单独打包的chunk的文件名需要配置chunkFilename和publicPath,chunkFilename:[name].js这样才会最终生成正确的路径和名字。