webpack.config.js檔案
const path = require('path');
let htmlwebpackplugin = require('html-webpack-plugin');//引入html-webpack-plugin插件
let export_html= {
entry: {
main:__dirname+"/app/js/main.js",//入口檔案
main1:__dirname+"/app/js/main1.js",//入口檔案
},
output: {
path: __dirname+"/_build/",
filename: "js/[name].js",//産出檔案,name根據entry的入口檔案鍵名定
},
module: {
loaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
]
}
,
plugins: [
//new一個模闆出來,這一個不使用chunks
new htmlwebpackplugin({
template: './app/home.html',//入口檔案
filename: 'home1.html',//産出檔案
}),
//new一個模闆出來
new htmlwebpackplugin({
template: './app/home.html',//入口檔案
filename: 'home2.html',//産出檔案
chunks : ['main'],//可以設定chunks按需引入JS檔案,不設定就會引入所有産出的js
chunksSortMode: 'manual',//将chunks按引入的順序排序,不用這個的話,引入到html的JS可能是錯亂排序的
})
]
};
module.exports=export_html;
看plugins這裡
//new一個模闆出來,這一個不使用chunks
new htmlwebpackplugin({
template: './app/home.html',
filename: 'home1.html',// 會生成home1.html
}),
//new一個模闆出來
new htmlwebpackplugin({
template: './app/home.html',
filename: 'home2.html',//會生成home2.html
chunks : ['main'],//注意:chunks裡面的值是對應entry入口的鍵名來的
chunksSortMode: 'manual',
})
app目錄下的home.html檔案

_build目錄下的home1.html檔案
_build目錄下的home2.html檔案
可以看到,home1.html引入了兩個js檔案,而且main1.js排在main.js前面,
而home2.html,隻引入了指定的main.js;
在home2.html的chunks加上:main1
//new一個模闆出來
new htmlwebpackplugin({
template: './app/home.html',//入口檔案
filename: 'home2.html',//産出檔案
chunks : ['main',"main1"],//可以設定chunks按需引入JS檔案,不設定就會引入所有産出的js
chunksSortMode: 'manual',//将chunks按引入的順序排序,不用這個的話,引入到html的JS可能是錯亂排序的
})
因為chunks裡,main在main1之前,是以引入的檔案也是按照這個順序來的;
順序的問題主要歸功于:這一條屬性
chunksSortMode: 'manual',//将chunks按引入的順序排序,不用這個的話,引入到html的JS可能是錯亂排序的
更進一步:
每次都這樣new很麻煩,故而寫個函數簡化過程
let get_html = function(name,chunk){//封裝
return {
template: './app/ejs for html/'+ name + '.ejs',
filename: name+ '.html',
chunks : ['main',chunk||name],//可以設定chunks按需引入JS檔案,不設定就會引入所有産出的js
chunksSortMode: 'manual',//将chunks按引入的順序排序
inject : true,
hash : true,
xhtml : true
}
};
然後在plugin裡面new一個測試一下;
此時,webpack.config.js:
const path = require('path');
let htmlwebpackplugin = require('html-webpack-plugin');//引入html-webpack-plugin插件
let get_html = function(name,chunk){//封裝
return {
template: './app/'+ name + '.html',
filename: name+ '.html',
chunks : ['main',chunk||null],//這裡引入公共檔案main.js,另外一個檔案按需引入,當然也可以把這個的值設為數組,傳入function的第二個值用數組就行
chunksSortMode: 'manual',//将chunks按引入的順序排序
inject : true,//所有JavaScript資源插入到body元素的底部
hash : true,//避免緩存
xhtml : true //規範html書寫
}
};
let export_html= {
entry: {
main:__dirname+"/app/js/main.js",//入口檔案
main1:__dirname+"/app/js/main1.js",//入口檔案
},
output: {
path: __dirname+"/_build/",
filename: "js/[name].js",//産出檔案,name根據entry的入口檔案鍵名定
},
module: {
loaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
]
}
,
plugins: [
//new一個模闆出來測試一下
new htmlwebpackplugin(get_html("home","main1"))
]
};
module.exports=export_html;
結果:
成功!
本文作者:qiangdada
本文釋出時間:2018/03/22
本文來自雲栖社群合作夥伴
開源中國,了解相關資訊可以關注oschina.net網站。