注意:
本文假設(shè)你有webpack 的基礎(chǔ)認識善茎。
本文的目的是異步加載js
項目結(jié)構(gòu)如下所示:
開始實戰(zhàn)
創(chuàng)建一個目錄<code>webpack-demo3</code>,并安裝<code>wbepack</code>。
mkdir webpack-demo3 && cd webpack-demo3
npm init -y
npm install --save-dev webpack
安裝<code>html-webpack-plugin</code>
npm install html-webpack-plugin --save-dev
新建<code>index.html</code>文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
新建<code>a.js</code>文件
module.exports=function dom(elem){
return document.querySelector(elem)
}
新建<code>b.js</code>文件
module.exports=function say(elem){
console.log('今天天氣真好');
}
新建<code>index.js</code>文件
require('./b')();
require.ensure([], function (require) {
const dom = require('./a.js');
dom('#root').innerHTML = 'hello world';
});
webpack 在構(gòu)建時,會靜態(tài)解析(statically parse)代碼中的 require.ensure()。在其中任何被引用的依賴模塊钱雷,或在回調(diào)函數(shù)中被 require() 的模塊纤房,都將被分離到一個新的 chunk 中。這個新的 chunk 會被生成為異步的 bundle暮现,由 webpack 通過 jsonp 來按需加載。
新建<code>webpack.config.js</code>文件
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:'./index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'dist')
},
plugins:[
new HtmlWebpackPlugin({
template:'index.html',
filename:'index.html',
inject:'body'
})
]
}
HtmlWebpackPlugin該插件將所有生成的js文件自動引入index.html中楚昭。當(dāng)文件名帶有hash值時栖袋,這個插件尤其有用。
HtmlWebpackPlugin會根據(jù)模版生成一個新的html文件哪替。
打包代碼:‘
webpack --config webpack.config.js
你會發(fā)現(xiàn)在dist文件夾中栋荸,生成了0.bundle.js,bundle.js,index.html
查看每個文件,你會發(fā)現(xiàn)凭舶,b.js和index.j的代碼被打包到了bundle.js中晌块。而a.js中的代碼被打包到了0.bundle.js。
index.html中只包含了一個script標(biāo)簽( <script type="text/javascript" src="bundle.js"></script>)帅霜,因為0.bundle.js將通過bundle.js異步加載匆背。