webpack自動生成項目的html

1 自動生成多個html頁面

設置webpack.config.js中的plugins屬性,屢次調用plugin插件(new htmlWebpackPlugin()),同時設置對應數量的.js入口文件javascript

2 指定生成的.html頁面中包含的chunk

設置屬性 chunks 或者 excludeChunkshtml

plugins: [
	new htmlWebpackPlugin({
		//filename:'index-[hash].html',
		filename:'a.html',
		template: 'index.html',
		//inject:'head',
		//inject:'body',
		inject:false, //爲false默認不生成外鏈引入
		title:'this is a.html',
		//chunks:['main','a']
		excludeChunks:['b','c']		
	})

3 把初始化的腳本直接嵌入頁面

  • (不須要http請求 提升腳本的加載速度和運行速度)而不以連接的形式引入到頁面
  • 在能夠經過inline的方式注入js文件的同時,是沒有辦法再加入內聯js,若是不使用compilation.assets的話是會一直報錯的,能夠看看插件做者的代碼
  • compilation.assets是webpack暴露出來能夠獲取文件數據的方法。經過傳文件名路徑進這個對象,拿到這個文件的索引,經過調用source拿到文件內容。 compilation.assets須要的是不帶publicPath,htmlWebpackPlugin.files.chunks.main.entry帶publicPatch,因此用substr()截取。
內連方式引入
<script type="text/javascript" >
		<%= 
		compilation.assets[htmlWebpackPlugin.files.chunks.main.entry.substr(htmlWebpackPlugin.files.publicPath.length)].source()
		%>
</script>
外聯方式引入
src:
<% for (var k in htmlWebpackPlugin.files.chunks) {%>
	<% if (k !== 'main') {%>
	<script type="text/javascript" src="<%= htmlWebpackPlugin.files.chunks[k].entry %>"></script>
	<% } %>
	<% } %>
相關文章
相關標籤/搜索