预期的目录结构如下:

  1. src
  2. |-- page
  3. |---- index
  4. |------ config.json
  5. |------ index.html
  6. |------ index.scss
  7. |------ index.js

config.json的配置大概是这样的:

  1. {
  2. "title": "首页",
  3. "filename": "index",
  4. "template": "index.html",
  5. "entry": "index.js"
  6. }

“title”: “页面名称”,
“filename”: “生成的文件名”,
“template”: “模板名称”,
“entry”: “入口文件”

安装插件

  1. npm install html-webpack-plugin --save-dev
  2. # 如果运行过程中有出现警告可以直接安装最新版
  3. # npm install html-webpack-plugin@next

代码思路

先看看html-webpack-plugin的用法

  1. const path = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. module.exports = {
  4. mode: 'development', // 区分开发还是生产环境
  5. stats: 'normal', // 控制输出的信息
  6. entry: {
  7. index: './src/pages/index/index.js',
  8. about: './src/pages/index/about.js'
  9. }, // 入口
  10. output: { // 出口
  11. path: path.resolve(__dirname, 'dist')
  12. },
  13. plugins: [
  14. new HtmlWebpackPlugin({
  15. title: '首页', // htmlWebpackPlugin.options.title
  16. filename: 'index.html', // 生成的文件名
  17. template: './src/pages/index/index.html', // 模板
  18. chunks: ['index'], // 插入的资源
  19. minify: false // 是否压缩
  20. }),
  21. new HtmlWebpackPlugin({
  22. title: '关于我们',
  23. filename: 'about.html',
  24. template: './src/pages/about/index.html',
  25. chunks: ['about'],
  26. minify: false
  27. })
  28. ], // 插件
  29. module: {
  30. rules: [] // loader
  31. }
  32. };

主要是组织,entry和plugins的数据。数据来源都是来自config.json。

实现代码

新建一个文件 webpack.read.pages.js,用来专门处理这个问题:

  1. const glob = require('glob');
  2. const path = require('path');
  3. const HtmlWebpackPlugin = require('html-webpack-plugin');
  4. class WebpackReadPages {
  5. config = './src/pages/**/config.json';
  6. entrys = {};
  7. htmlWebpackPlugins = [];
  8. constructor (config) {
  9. if (config) {
  10. this.config = config;
  11. }
  12. this.readConfig();
  13. }
  14. readConfig () {
  15. const files = glob.sync(this.config); // 获取匹配对应规则的文件
  16. const entrys = {}; // 入口
  17. const htmls = []; // html插件
  18. files.forEach(file => {
  19. const fileData = path.parse(file); // 解析路径
  20. const filePath = path.resolve(__dirname, file);
  21. const fileContent = require(filePath); // 获取配置文件内容
  22. entrys[fileContent.filename] = `${fileData.dir}/${fileContent.entry}`;
  23. htmls.push(new HtmlWebpackPlugin({
  24. title: fileContent.title,
  25. filename: `${fileContent.filename}.html`,
  26. template: `${fileData.dir}/${fileContent.template}`,
  27. chunks: [fileContent.filename],
  28. minify: false
  29. }));
  30. });
  31. this.entrys = entrys;
  32. this.htmlWebpackPlugins = htmls;
  33. }
  34. }
  35. module.exports = WebpackReadPages;

修改webpack.config.js

  1. const path = require('path');
  2. const WebpackReadPages = require('./webpack.read.pages');
  3. const webpackReadPages = new WebpackReadPages();
  4. let webpackPlugins = webpackReadPages.htmlWebpackPlugins;
  5. module.exports = {
  6. mode: 'development',
  7. stats: 'normal',
  8. entry: webpackReadPages.entrys,
  9. output: {
  10. path: path.resolve(__dirname, 'dist')
  11. },
  12. plugins: webpackPlugins,
  13. module: {
  14. rules: []
  15. }
  16. };

试试 npm run build,看起来是成功了。但是看起来css没有压缩,原因是mode: ‘development’,所以用cross-env来设置环境。

  1. npm install cross-env --save-dev

修改package.json

  1. {
  2. "name": "webpack-demo",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "build": "cross-env NODE_ENV=production webpack",
  8. "test": "echo \"Error: no test specified\" && exit 1"
  9. },
  10. "keywords": [],
  11. "author": "",
  12. "license": "MIT",
  13. "devDependencies": {
  14. "cross-env": "^7.0.3",
  15. "html-webpack-plugin": "^5.0.0-alpha.15",
  16. "webpack": "^5.10.0",
  17. "webpack-cli": "^4.2.0",
  18. "webpack-dev-server": "^3.11.0"
  19. }
  20. }

修改webpack.config.js

  1. const path = require('path');
  2. const env = process.env.NODE_ENV || 'production';
  3. const WebpackReadPages = require('./webpack.read.pages');
  4. const webpackReadPages = new WebpackReadPages();
  5. let webpackPlugins = webpackReadPages.htmlWebpackPlugins;
  6. module.exports = {
  7. mode: env,
  8. stats: 'normal',
  9. entry: webpackReadPages.entrys,
  10. output: {
  11. path: path.resolve(__dirname, 'dist')
  12. },
  13. plugins: webpackPlugins,
  14. module: {
  15. rules: []
  16. }
  17. };

打完收工!