webpack5_webpack多静态html项目打包

const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
  mode: 'development',
  entry: {
    index: './src/pages/index/app.js', // 首页
    detail: './src/pages/detail/app.js', // 详情页
    complaint: './src/pages/complaint/app.js', // 投诉界面
  },
  devtool: 'source-map',
  output: {
    path: resolve(__dirname, '../dist'),
    filename: 'js/[name]-bundle.js', // filename不能写死,只能通过[name]获取bundle的名字
    chunkFilename: 'js/[name]-bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader', 'postcss-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          { loader: MiniCssExtractPlugin.loader },
          'css-loader',
          'sass-loader',
          'postcss-loader',
        ],
      },
      /* 打包样式文件中的图片资源 */
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        type: 'asset',
        generator: {
          filename: 'media/img/[name].[ext]',
        },
      },
      /* 打包html中引用的资源 */
      {
        test: /\.html$/,
        use: {
          loader: 'html-withimg-loader',
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/pages/index/index.html',
      chunks: ['index'],
      filename: 'index.html',
    }),
    new HtmlWebpackPlugin({
      template: './src/pages/detail/detail.html',
      chunks: ['detail'],
      filename: 'detail.html',
    }),
    new HtmlWebpackPlugin({
      template: './src/pages/complaint/complaint.html',
      chunks: ['complaint'],
      filename: 'complaint.html',
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].css', // 生成的文件以10位hash值为文件名
    }),
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        // 打包业务中公共代码
        common: {
          name: 'common',
          chunks: 'initial',
          minSize: 1,
          priority: 0,
          minChunks: 2, // 同时引用了2次才打包
        },
        // 打包第三方库的文件
        vendor: {
          name: 'vendor',
          test: /[\\/]node_modules[\\/]/,
          chunks: 'initial',
          priority: 10,
          minChunks: 2, // 同时引用了2次才打包
        },
      },
    },
    runtimeChunk: { name: 'manifest' }, // 运行时代码
  },
  /* dev-serve 自动化编译 */
  devServer: {
    static: { directory: resolve(__dirname, '../dist') },
    hot: true,
    // static: { //托管静态资源文件
    //   directory: resolve(__dirname, "../public"),
    // },
    compress: true, //是否启动压缩 gzip
    port: 8080, // 端口号
    open: true, // 是否自动打开浏览器
    client: {
      //在浏览器端打印编译进度
      progress: true,
    },
  },
}

posted @ 2023-10-09 01:54  Syinho  阅读(144)  评论(0编辑  收藏  举报