webpack4.0核心概念(八)———— 多页面打包通用方案 MPA

未处理前的webpack.config.js文件【手动增加多页面】

//两个入口
entry: {
    index: "./src/index.js",
    login: "./src/login.js",
},
//出口
output: {
    path: path.resolve(__dirname, "./dist"),
    filename: "[name]-[hash:6].js",
},






//插件配置
 plugins: [
    new htmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html",
      chunks: ["main"],
    }),
    new htmlWebpackPlugin({
      template: "./src/index.html",
      filename: "login.html",
      chunks: ["login"],
    }),
    new CleanWebpackPlugin(),
    new miniCssExtractPlugin({
      filename: "css/index-[contenthash:6].css",
    }),
  ],

处理后的webpack.config.js文件【自动在项目目录中查找多页面】

首先改变目录结构

webpack.config.js主要代码如下

const glob = require("glob");//npm i glob -D

const setMpa = () => {
  const entry = {};
  const htmlWebpackPlugins = [];
  //生成entry
  const entryFiles = glob.sync(path.join(__dirname, "./src/*/index.js"));//目录下面有index.js的目录
  console.log(entryFiles)
  entryFiles.map((item, index) => {
    const entryFile = item;
    const match = entryFile.match(/src\/(.*)\/index\.js$/);
    console.log(match)
    const pageName = match[1];
    entry[pageName] = entryFile;
    
    htmlWebpackPlugins.push(
      new htmlWebpackPlugin({
        template: path.join(__dirname, `./src/${pageName}/index.html`),
        filename: `${pageName}.html`,
        chunks: [pageName, "detail"],
      })
    );
  });

  return {
    entry,
    htmlWebpackPlugins,
  };
};

const { entry, htmlWebpackPlugins } = setMpa();

module.exports = {
  entry,

  plugins: [
    ...htmlWebpackPlugins,
    new CleanWebpackPlugin(),
    new miniCssExtractPlugin({
      filename: "css/index-[contenthash:6].css",
    }),
  ],
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值