预期的目录结构如下:
src|-- page|---- index|------ config.json|------ index.html|------ index.scss|------ index.js
config.json的配置大概是这样的:
{"title": "首页","filename": "index","template": "index.html","entry": "index.js"}
“title”: “页面名称”,
“filename”: “生成的文件名”,
“template”: “模板名称”,
“entry”: “入口文件”
安装插件
npm install html-webpack-plugin --save-dev# 如果运行过程中有出现警告可以直接安装最新版# npm install html-webpack-plugin@next
代码思路
先看看html-webpack-plugin的用法
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = {mode: 'development', // 区分开发还是生产环境stats: 'normal', // 控制输出的信息entry: {index: './src/pages/index/index.js',about: './src/pages/index/about.js'}, // 入口output: { // 出口path: path.resolve(__dirname, 'dist')},plugins: [new HtmlWebpackPlugin({title: '首页', // htmlWebpackPlugin.options.titlefilename: 'index.html', // 生成的文件名template: './src/pages/index/index.html', // 模板chunks: ['index'], // 插入的资源minify: false // 是否压缩}),new HtmlWebpackPlugin({title: '关于我们',filename: 'about.html',template: './src/pages/about/index.html',chunks: ['about'],minify: false})], // 插件module: {rules: [] // loader}};
主要是组织,entry和plugins的数据。数据来源都是来自config.json。
实现代码
新建一个文件 webpack.read.pages.js,用来专门处理这个问题:
const glob = require('glob');const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');class WebpackReadPages {config = './src/pages/**/config.json';entrys = {};htmlWebpackPlugins = [];constructor (config) {if (config) {this.config = config;}this.readConfig();}readConfig () {const files = glob.sync(this.config); // 获取匹配对应规则的文件const entrys = {}; // 入口const htmls = []; // html插件files.forEach(file => {const fileData = path.parse(file); // 解析路径const filePath = path.resolve(__dirname, file);const fileContent = require(filePath); // 获取配置文件内容entrys[fileContent.filename] = `${fileData.dir}/${fileContent.entry}`;htmls.push(new HtmlWebpackPlugin({title: fileContent.title,filename: `${fileContent.filename}.html`,template: `${fileData.dir}/${fileContent.template}`,chunks: [fileContent.filename],minify: false}));});this.entrys = entrys;this.htmlWebpackPlugins = htmls;}}module.exports = WebpackReadPages;
修改webpack.config.js
const path = require('path');const WebpackReadPages = require('./webpack.read.pages');const webpackReadPages = new WebpackReadPages();let webpackPlugins = webpackReadPages.htmlWebpackPlugins;module.exports = {mode: 'development',stats: 'normal',entry: webpackReadPages.entrys,output: {path: path.resolve(__dirname, 'dist')},plugins: webpackPlugins,module: {rules: []}};
试试 npm run build,看起来是成功了。但是看起来css没有压缩,原因是mode: ‘development’,所以用cross-env来设置环境。
npm install cross-env --save-dev
修改package.json
{"name": "webpack-demo","version": "1.0.0","description": "","main": "index.js","scripts": {"build": "cross-env NODE_ENV=production webpack","test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "MIT","devDependencies": {"cross-env": "^7.0.3","html-webpack-plugin": "^5.0.0-alpha.15","webpack": "^5.10.0","webpack-cli": "^4.2.0","webpack-dev-server": "^3.11.0"}}
修改webpack.config.js
const path = require('path');const env = process.env.NODE_ENV || 'production';const WebpackReadPages = require('./webpack.read.pages');const webpackReadPages = new WebpackReadPages();let webpackPlugins = webpackReadPages.htmlWebpackPlugins;module.exports = {mode: env,stats: 'normal',entry: webpackReadPages.entrys,output: {path: path.resolve(__dirname, 'dist')},plugins: webpackPlugins,module: {rules: []}};
打完收工!
