webpack多页面打包

142 阅读1分钟

多⻚⾯应⽤(MPA):

每⼀次⻚⾯跳转的时候,后台服务器都会给返回⼀个新的 html ⽂档,

这种类型的⽹站也就是多⻚⽹站,也叫做多⻚应⽤。

多⻚⾯打包基本思路:

动态获取 entry 和设置 html-webpack-plugin 数量
const path = require("path");
const glob = require("glob");
const HtmlWebpackPlugin = require("html-webpack-plugin");
//动态获取entry
const entryFiles = glob.sync(path.join(__dirname, "./src/*/index.js")); 
const entry = {};
const HtmlWebpackPlugins = [];
entryFiles.map((entryFile) => {
  const match = entryFile.match(/src\/(.*)\/index\.js/);
  const pageName = match && match[1];
  entry[pageName] = entryFile;
  //动态增加htmlwebpack
  HtmlWebpackPlugins.push(
    new HtmlWebpackPlugin({
      template: path.join(__dirname, `./src/${pageName}/index.js`),
      filename: `${pageName}.html`,
      chunks: [pageName],
      //css、js自动注入html
      inject: true,
      // minify: { 
      // }
    })
  );
}); 

module.exports = {
  entry: entry,
  output: {
    path: path.join(__dirname, "dist"),
    filename: "[name].js",
  }, 
  plugins: HtmlWebpackPlugins,