webpack4.x 系列(五) ☞ webpack多頁面打包

單頁面應用:整個應用裏面只有一個html文件。現在主流的框架,vue,react都是單頁面應用。所以webpack絕大部分都是對單頁面打包。那麼webpack如何對多頁面進行打包

目錄:

|- build
 |- webpack.common.js//公共webpack
 |- webpack.dev.js// 開發模式webpack,前期用merge合併
 |- webpack.prod.js// 生產模式webpack,前期用merge合併
|- src
 |- index.html// 模板文件
 |- index.js// index入口
 |- make.js// make.js入口
|- package.json

index.html與make.js

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<!-- 可以用htmlWebpackPlugin的title作爲目錄 -->
	<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
	<div id='root'></div>
</body>
</html>

index.js 與 make.js 兩個文件都一樣(代碼如下),我這裏用了react作爲源文件,或者你可以根據自己的意願寫這兩個文件的源代碼,隨便你怎麼寫,這章的目的是多頁打包。

import React, { Component } from 'react';
import ReactDom from 'react-dom';
import _ from 'lodash';

class App extends Component {
	render() {
		return (
			<div>
				<div>{_.join(['This', 'is', 'App'], ' ')}</div>
			</div>
		)
	}
}

ReactDom.render(<App />, document.getElementById('root'));

webpack.common.js

entry入口配置:

  // 入口文件
  entry: {
    index: './src/index.js',
    make: './src/make.js'
  },

plugins的配置:

plugins : [
  // HtmlWebpackPlugin會在打包結束後,自動生成一個html文件,並把打包生成的js自動引入到這個html文件中
  new HtmlWebpackPlugin({
    template: 'src/index.html',
    filename: 'index.html',
        title: 'index',
    chunks: ['vendors', 'main']
  }),
  new HtmlWebpackPlugin({
    template: 'src/index.html',
    filename: 'make.html',
       title: 'make'
    chunks: ['vendors', 'list']
  }),
    // 用於清除dist目錄
  new CleanWebpackPlugin()
];

這樣子的多頁打包就結束了。也可以進行正常的多頁面打包了。執行打包命令npm run xxx,dist目錄下就會多出兩個html文件

裏面的配置參數說明:

主要內容:

  • inject: true | body | head |false
  • chunks:允許插入到模板中的一些chunk,不配置此項默認會將entry中所有的chunk注入到模板中。在配置多個頁面時,每個頁面注入的thunk應該是不相同的,需要通過該配置爲不同頁面注入不同的chunk。
  • excludeChunks:這個與chunks配置項正好相反,用來配置不允許注入的thunk。

雖然說結束了,不過,如果頁面入口一多的話,HtmlWebpackPlugin也會多起來,我們就會想到優化整合。

優化:

我先貼出代碼,然後看我寫的註釋說明:

const makePlugins = (configs) => {
    // 獲取key值,然後以數組的方式顯示
    Object.keys(configs.entry).forEach(item => {
        // 每遍歷一次就往裏面添加HtmlWebpackPlugin
		plugins.push(
			new HtmlWebpackPlugin({
				template: 'src/index.html',
				filename: `${item}.html`,
				chunks: ['runtime', 'vendors', item]
			})
		)
	});
    return plugins;
}

// 通過對象的方式,給configs添加個plugins屬性,屬性名爲makePlugins(configs)的的返回值
configs.plugins = makePlugins(configs);
// 起個名字,然後導出去
module.exports = configs;

優化完畢!這樣子可以減少很多HtmlWebpackPlugin的代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章