webpack 构建多页面应用的入口以及HtmlWebpackPlugin配置文件

项目是 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
}

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值