單頁面下的基本配置
webpack.config.js
var htmlWebpackPlugin=require('html-webpack-plugin')
module.exports={
entry:{
main:'./src/script/main.js',
a:'./src/script/a.js',
},
output:{
path:'/Users/flyme/Documents/web/learn/learn_webpack/webpack-demo/dist',
filename:'js/[name]-[chunkhash].js',
publicPath:'http://cdn.com/'//引入js的默認路徑,上線時很又用
},
plugins:[
new htmlWebpackPlugin({//有兩個屬性files和optios
template:'index.html',//將script標簽引入到index.html中
//filename:'index-[hash].html',//生成的html文件的名字,若是這樣寫每次更新都會根據(jù)hash重新生成這個html 文件
filename:'index.html',
inject:'head',//script標簽被嵌入到哪里,
title:'hello,i am title',//在html的title標簽中使用ejs的寫法引入<%= htmlWebpackPlugin.options.title %>
minify:{//對當前生成的html文件進行壓縮
removeComments:true,//刪除注釋
collapseWhitespace:true//刪除空格
}
})
]
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
<script src="<%=htmlWebpackPlugin.files.chunks.main.entry%>"></script>
</head>
<body>
<% for(var key in htmlWebpackPlugin.files){%>
<%= key%>:<%= htmlWebpackPlugin.files[key]%>
<%}%>
我是分割線
<% for(var key in htmlWebpackPlugin.options){%>
<%= key%>:<%= htmlWebpackPlugin.options[key]%>
<%}%>
<script src="<%=htmlWebpackPlugin.files.chunks.a.entry%>"></script>
</body>
</html>
多頁面,生成多個html
plugins[]是數(shù)組形式,可以通過new很多個htmlWebpackPlugin對象來生成很多個html。
通過chunks或者excludechunks來制定需要加載的js
注意:
之前在html頁面中有script標簽中不能通過編碼點的方式引入不是所有頁面的chunk中共有的js文件,否則就會報錯,即使注釋掉也不行
var htmlWebpackPlugin=require('html-webpack-plugin')
module.exports={
entry:{
main:'./src/script/main.js',
a:'./src/script/a.js',
b:'./src/script/b.js',
c:'./src/script/c.js'
},
output:{
path:'/Users/flyme/Documents/web/learn/learn_webpack/webpack-demo/dist',
filename:'js/[name]-[chunkhash].js',
publicPath:'http://cdn.com/'//引入js的默認路徑,上線時很有用
},
plugins:[
//多頁面,好多個html
new htmlWebpackPlugin({
template:'index.html',
filename:'a.html',
inject:false,
title:'this is a.html',
//chunks:['main','a']//使用chunks一定注意了index.html中不能有script標簽,注釋掉都不行,會報錯的
excludeChunks:['b','c']//不需引入的js
}),
new htmlWebpackPlugin({
template:'index.html',
filename:'b.html',
inject:false,
title:'this is b.html',
chunks:['b','main']//需要引入的js
}),
new htmlWebpackPlugin({
template:'index.html',
filename:'c.html',
inject:false,
title:'this is c.html',
chunks:['c','main']
})
]
}
若想通過提前加載一些js文件,減少固定請求,則需要在html模版中書寫script標簽,并在標簽中導入默認加載的js文件(當然前提是所有頁面的chunks里都得加載了此js文件,做的時候沒有就一只報錯,這是個坑),當然其他文件的應(yīng)用就要排除這個默認引用的了,所以就把inject設(shè)置為false,使它不默認導入js,并在index.html模版中通過代碼方式引入,代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
<script type='text/javascript'>
<%=
compilation.assets[htmlWebpackPlugin.files.chunks.main.entry.substr(htmlWebpackPlugin.files.publicPath.length)].source() %>
</script>
</head>
<body>
<% for(var k in htmlWebpackPlugin.files.chunks){%>
<%if(k!=='main'){%>
<script src="<%= htmlWebpackPlugin.files.chunks[k].entry%>"></script>
<%}%>
<%}%>
</body>
</html>