单页面应用:整个应用里面只有一个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的代码。