懶加載或者按需加載,可以優化網頁或應用。
webpack 懶加載學習
例子鏈接:懶加載/demo15/
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
// const webpack = require('webpack');
module.exports = {
entry: {
app: './src/index.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
+ chunkFilename: '[name].bundle.js'
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management'
}),
]
}
filename:對應於entry裏面生成出來的文件名
chunkFilename:chunkname就是未被列在entry中,異步加載模塊時會用到這個。
新建 print.js
console.log('The print.js module has loaded! See the network tab in dev tools...');
export default () => {
console.log('Button Clicked: Here\'s "some text"!');
}
新建test.js
console.log('按需加載,厲害了')
export function test() {
console.log('test')
}
修改 index.js,
import _ from 'lodash';
function buttonCreat(element,text) {
var button = document.createElement('button');
var br = document.createElement('br');
button.innerHTML =text;
element.appendChild(br);
element.appendChild(button);
return button
// Note that because a network request is involved, some indication
// of loading would need to be shown in a production-level site/app.
}
function component() {
var element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
let btn1 = buttonCreat(element,'Click me and look at the console!')
let btn2 = buttonCreat(element,'test.js 測試')
btn1.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => {
var print = module.default;
print();
});
btn2.onclick = e=>import(/* webpackChunkName: "test" */'./test').then(module=>{
var test = module.test
test()
})
return element;
}
document.body.appendChild(component());
這裏關鍵代碼
btn2.onclick = e=>import(/* webpackChunkName: "test" */'./test').then(module=>{
var test = module.test
test()
})
webpackChunkName的意思是定義一個打包後的名字,結合chunkFilename使用。webpack打包後爲 print.bundle.js、 test.bundle.js
運行命令 npm run build
,可以看到打包的文件
Built at: 08/14/2019 5:37:21 PM
Asset Size Chunks Chunk Names
app.bundle.js 72.2 KiB 0 [emitted] app
index.html 192 bytes [emitted]
print.bundle.js 250 bytes 1 [emitted] print
test.bundle.js 207 bytes 2 [emitted] test
此處也可以不用,
btn2.onclick = e=>import('./test').then(module=>{
var test = module.test
test()
})
那麼打包後文件是1.bundle.js,2.bundle.js,這是 webpack 默認給的名字。
運行npm run build,可以看到不使用webpackChunkName後,生成 js 文件變爲了1.bundle.js,2.bundle.js
Built at: 08/14/2019 5:35:29 PM
Asset Size Chunks Chunk Names
1.bundle.js 250 bytes 1 [emitted]
2.bundle.js 207 bytes 2 [emitted]
app.bundle.js 72.2 KiB 0 [emitted] app
index.html 192 bytes [emitted]