之前几天的Webpack中我们说到的所有的打包的都是只针对于单个页面的打包,甚至是一些脚手架工具中的webpack页面打包都是单页面的。但是当我们需要打包出多个html页面时,我们又应该怎么搞定呢?
- 关于多页应用的打包其实不是webpack的内容,而是我们需要如何使用nodejs去实现多个页面的打包:假设我们现在有如下一个简单配置文件:
const path = require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const AddAssetHtmlWebpackPlugin = require("add-asset-html-webpack-plugin")
const webpack = require('webpack')
const fs = require('fs')
module.exports = {
mode: "development",
entry: {
index: path.join(__dirname, "src/index.js"),
},
output: {
filename: "[name].js",
path: path.join(__dirname, "dist")
},
plugin: [
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: `index.html`,
chunks: "./src/index.js" // 指定html文件中需要引入的js文件
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"]
}
}
}
]
}
}
- 现在假设我们需要同时再打包出一个新的html文件到dist目录下,我们可以直接在plugin中再New一个htmlWebpackPlugin(),此时再在entry中加入我们页面打包的入口即可,如下所示:
// ....
entry: {
index: path.join(__dirname, "src/index.js"),
list: path.join(__dirname, "src/list.js")
}
- 但是如上这样的增加会导致一个问题: 当我们需要的页面很多时,我们一个一个的这样去给每个打包的入口文件加htmlWebpackPlugin()模板生成插件会很麻烦,也会使得代码很冗余,所以我们需要让js帮助我们自动的去生成这个htmlWebpackPlugin()的插件配置:
- 我们先将默认的公共的配置项写出来:
const path = require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const AddAssetHtmlWebpackPlugin = require("add-asset-html-webpack-plugin")
const webpack = require('webpack')
const fs = require('fs')
// 该文件需要导出webpack的配置对象
const config = {
mode: "development",
entry: {
index: path.join(__dirname, "src/index.js"),
list: path.join(__dirname, "src/list.js")
},
output: {
filename: "[name].js",
path: path.join(__dirname, "dist")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"]
}
}
}
]
}
}
module.exports = config
- 定义一个生成plugin配置项的函数,该函数中我们可以根据入口(entry)项中生成的函数去生成多个页面的模板:
function createPlugin(config){
const plugins = [
new CleanWebpackPlugin()
]
Object.keys(config.entry).forEach(item => {
plugins.push(
new HtmlWebpackPlugin({
template: "./src/index.html",'
filename: `${item}.html`,
chunks: [item]
})
)
})
return plugins
}
- 调用当前函数生成完整的配置文件:
config.plugins = createPlugin(config)
module.exports = config
当然这里在这个createPlugin函数中我们还可以根据实际的需要去生成更多的插件,甚至如果我们觉得我们这里写了太多的entry配置项太麻烦,我们也可以用js去动态的生成这个entry,这里提供一个思路: 我们可以使用nodejs文件操作的模块去读取src目录,遍历src目录下的js文件,而哪些是我们需要进行打包的js入口我们可以依据实际情况进行筛选,然后遍历生成我们的entry配置项
下一次我们将玩点有意思的,自己去实现一个简单的webpack打包,当然这也是我们webpack之旅的最终章了