vue2使用webpack优化打包体积过大、打包慢问题

压缩图片

在本项目中使用了大量图片,打包查看图片所占体积最大,使用image-webpack-loader压缩图片

 chainWebpack(config) {
    
    
    // 压缩图片
    config.module
      .rule("images")
      .use("url-loader")
      .tap((options) => ({
    
    
        limit: 10240, 
        fallback: {
    
    
          loader: require.resolve("file-loader"),
          options: {
    
    
            name: "static/img/[name].[hash:8].[ext]",
            esModule: false, //低版本默认为false,高版本默认为true
          },
        },
      }))
      .end()
      .use("image-webpack-loader")
      .loader("image-webpack-loader")
      .options({
    
    
        mozjpeg: {
    
    
          progressive: true,
          quality: 50,
        }, // 压缩JPEG图像
        optipng: {
    
    
          enabled: true,
        }, // 压缩PNG图像
        pngquant: {
    
    
          quality: [0.5, 0.65],
          speed: 4,
        }, // 压缩PNG图像
        gifsicle: {
    
    
          interlaced: false,
        }, // 压缩GIF图像
      })
      .end()
      .enforce("post"); 
      }

多进程打包

使用happypack

const HappyPack = require("happypack");
const happyThreadPool = HappyPack.ThreadPool({
    
    
  size: 6,
}); //线程城池

config.when(process.env.NODE_ENV !== "development", (config) => {
    
    
      config
        .plugin("happypack")
        .use(HappyPack)
        .tap((options) => {
    
    
          options[0] = {
    
    
            id: "babel",
            loaders: ["babel-loader?cacheDirectory=true"],
            threadPool: happyThreadPool,
          };
          return options;
        });
       })

打包去除debugger和console

UglifyJsPlugin

const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
config.when(process.env.NODE_ENV !== "development", (config) => {
    
    
  config.optimization.minimizer = [
        //比较慢,开发环境关闭
        new UglifyJsPlugin({
    
    
          uglifyOptions: {
    
    
            compress: {
    
    
              warnings: false,
              drop_console: true, //console
              drop_debugger: true,
              pure_funcs: ["console.log"], //移除console
            },
            // output: {
    
    
            //   comments: false, //去掉注释
            //   },
          },
          sourceMap: false,
          parallel: true, //使用多进程并行运行来提高构建速度
        }),
      ];
   })

splitChunks公共模块

  config.optimization.splitChunks({
    
    
        chunks: "all",
        cacheGroups: {
    
    
          libs: {
    
    
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial",
          },
          elementUI: {
    
    
            name: "chunk-elementUI",
            priority: 20,
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
          },
          commons: {
    
    
            name: "chunk-commons",
            test: resolve("src/components"),
            minChunks: 3,
            priority: 5,
            reuseExistingChunk: true,
          },
        },
      });

整个配置

const path = require("path");
const webpack = require("webpack");
const defaultSettings = require("./src/settings.js");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const HappyPack = require("happypack");
const happyThreadPool = HappyPack.ThreadPool({
    
    
  size: 6,
}); //线程城池
// const CompressionWebpackPlugin = require("compression-webpack-plugin"); //安装npm i [email protected]

function resolve(dir) {
    
    
  return path.join(__dirname, dir);
}

const name = defaultSettings.title || "YDCLOUD";
// 开发端口
const port = process.env.port || process.env.npm_config_port || 9528;
// 后台网关地址
const url = process.env.VUE_APP_BASE_API;

module.exports = {
    
    
  runtimeCompiler: true,
  lintOnSave: true,
  productionSourceMap: false,
  css: {
    
    
    loaderOptions: {
    
    
      sass: {
    
    
        // additionalData: `@import "~@/YDCLOUD/assets/theme/variable.scss";`
        sassOptions: {
    
    
          outputStyle: "expanded",
        },
      },
    },
  },
  // 本地开发环境配置
  devServer: {
    
    
    port: port,
    host: "0.0.0.0",
    open: true,

    disableHostCheck: true,
    // 转发代理
    proxy: {
    
    
      "/coreframe": {
    
    
        target: url,
        ws: true,
        changeOrigin: true,
        pathRewrite: {
    
    
          "^/coreframe": "/coreframe",
        },
      }
    },
  },
  configureWebpack: {
    
    
    name: name,
    resolve: {
    
    
      alias: {
    
    
        "@": resolve("src"),
      },
    },
    plugins: [
      new webpack.ProvidePlugin({
    
    
        $: "jquery",
        jQuery: "jquery",
        "windows.jQuery": "jquery",
      }),
      // new HappyPack({
    
    
      //   id: 'happyBabel',
      //   loaders: ['babel-loader?cacheDirectory=true'],
      //   threadPool: happyThreadPool
      // })
    ],
  },
  chainWebpack(config) {
    
    
    // 压缩图片
    config.module
      .rule("images")
      .use("url-loader")
      .tap((options) => ({
    
    
        limit: 10240, 
        fallback: {
    
    
          loader: require.resolve("file-loader"),
          options: {
    
    
            name: "static/img/[name].[hash:8].[ext]",
            esModule: false, //低版本默认为false,高版本默认为true
          },
        },
      }))
      .end()
      .use("image-webpack-loader")
      .loader("image-webpack-loader")
      .options({
    
    
        mozjpeg: {
    
    
          progressive: true,
          quality: 50,
        }, // 压缩JPEG图像
        optipng: {
    
    
          enabled: true,
        }, // 压缩PNG图像
        pngquant: {
    
    
          quality: [0.5, 0.65],
          speed: 4,
        }, // 压缩PNG图像
        gifsicle: {
    
    
          interlaced: false,
        }, // 压缩GIF图像
      })
      .end()
      .enforce("post"); // 表示先执行配置在下面那个loader,即image-webpack-loader

    config.plugin("preload").tap(() => [
      {
    
    
        rel: "preload",
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: "initial",
      },
    ]);

    config.plugins.delete("prefetch");
    config.when(process.env.NODE_ENV !== "development", (config) => {
    
    
      // 对超过10kb的文件gzip压缩
      // config.plugin("compressionPlugin").use(
      //   new CompressionWebpackPlugin({
    
    
      //     test: /\.(js|css|html)$/, // 匹配文件名
      //     threshold: 10240,
      //   })
      // );

      config
        .plugin("happypack")
        .use(HappyPack)
        .tap((options) => {
    
    
          options[0] = {
    
    
            id: "babel",
            loaders: ["babel-loader?cacheDirectory=true"],
            threadPool: happyThreadPool,
          };
          return options;
        });

      const hRule = config.module.rule("js");
      hRule.test(/\.js$/).include.add(resolve("src")).end();
      hRule.uses.clear();
      hRule
        .use("happypack/loader?id=babel")
        .loader("happypack/loader?id=babel")
        .end();

      config
        .plugin("ScriptExtHtmlWebpackPlugin") // HTML 内联或外部加载脚本支持
        .after("html")
        .use("script-ext-html-webpack-plugin", [
          {
    
    
            // `runtime`必须与runtimeChunk名称相同。默认值为`runtime`
            inline: /runtime\..*\.js$/,
          },
        ])
        .end();
      config.optimization.minimizer = [
        //比较慢,开发环境关闭
        new UglifyJsPlugin({
    
    
          uglifyOptions: {
    
    
            compress: {
    
    
              warnings: false,
              drop_console: true, //console
              drop_debugger: true,
              pure_funcs: ["console.log"], //移除console
            },
            // output: {
    
    
            //   comments: false, //去掉注释
            //   },
          },
          sourceMap: false,
          parallel: true, //使用多进程并行运行来提高构建速度
        }),
      ];
      config.optimization.splitChunks({
    
    
        chunks: "all",
        cacheGroups: {
    
    
          libs: {
    
    
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial",
          },
          elementUI: {
    
    
            name: "chunk-elementUI",
            priority: 20,
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
          },
          commons: {
    
    
            name: "chunk-commons",
            test: resolve("src/components"),
            minChunks: 3,
            priority: 5,
            reuseExistingChunk: true,
          },
        },
      });
      config.optimization.runtimeChunk("single");
    });
  },
};

猜你喜欢

转载自blog.csdn.net/Pure_White520/article/details/132182073