项目是 electron-vue 应用,其中有多个页面,那就需要在配置 webpack 的入口 entry 时,采用对象方式配置,以及统一配置 HtmlWebpackPlugin。
需要打包内容的目录结构:
- src
- pages
- page1
- router
- store
- view
- App.vue
- main.js
- index.ejs
- page2
同上
- page3
同上
......
做法:
1. 创建 muti-page.config.js 配置文件
2. 安装引入 path(获取路径)、glob(获取匹配对应规则的文件)、html-webpack-plugin(生成HTML文件)
3. 配置 entry 和 HtmlWebpackPlugin
代码:
const glob = require('glob'); // 获取匹配对应规则的文件
const path = require('path');
const PAGE_PATH = path.resolve(__dirname, './src');
// 生成一个H5文件,并将webpack生成的bundle.js用script标签插入到文件中
const HtmlWebpackPlugin = require('html-webpack-plugin');
exports.entries = function () {
// 用于匹配 pages 下一级文件夹中的 main.js 文件
// glob.sync 可以同步获取匹配文件列表
const entryFiles = glob.sync(PAGE_PATH + '/*/main.js');
let map = {};
entryFiles.forEach(filePath => {
// 下述两句代码用于取出 pages 下一级文件夹的名称
const entryPath = path.dirname(filePath);
const filename = entryPath.substring(entryPath.lastIndexOf('\/') + 1);
/* 生成对应的键值对 */
map[filename] = filePath;
})
return map;
}
exports.htmlPlugin = function () {
const entryHtml = glob.sync(PAGE_PATH + '/*/index.ejs');
let arr = [];
entryHtml.forEach(filePath => {
const entryPath = path.dirname(filePath);
const filename = entryPath.substring(entryPath.lastIndexOf('\/') + 1);
let conf = {
template: filePath,
filename: filename + `/index.html`,
chunks: ['manifest', 'vendor', filename]
}
if (process.env.NODE_ENV === 'production') {
let productionConfig = {
minify: {
removeComments: true, // 移除注释
collapseWhitespace: true, // 删除空白符和换行符
removeAttributeQuotes: true // 移除属性引号
},
chunksSortMode: 'dependency' // 对引入的chunk模块进行排序
}
conf = {...conf, ...productionConfig}; //合并基础配置和生产环境专属配置
}
arr.push(new HtmlWebpackPlugin(conf))
})
return arr
}