webpack5使用插件ImageMinimizerWebpackPlugin打包报错

发布于 2022-09-13 00:59:51 字数 8201 浏览 21 评论 0

以下是我的webpack.config.js文件:

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const StylelintPlugin = require('stylelint-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
module.exports = (env, argv) => {
  const config = {
    mode: 'development',
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: resolve(__dirname, 'dist')
    },
    optimization: {
      minimize: false,   ////开发环境优化CSS
      // minimizer: [
      //   new CssMinimizerPlugin({
      //     parallel: true,  //使用多进程并发执行,提升构建速度
      //   }),
      // ]
    },
    module: {
      rules: [
        // 使用资源模块处理字体
        {
          test: /\.(eot|svg|ttf|woff|woff2)$/i,
          type: 'asset/resource',
          generator: {
            filename: 'fonts/[name].[hash:5][ext]'
          }
        },
        //处理CSS
        {
          test: /\.css$/,
          use: [
            // 'style-loader',
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',],
        },
        // 处理Less
        {
          test: /\.less$/,
          use: [
            // 'style-loader',
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',
            'less-loader'
          ]
        },
        // 资源模块处理图片
        {
          test: /\.(png|jpe?g|gif)$/i,
          type: "asset",
          parser: {
            dataUrlCondition: {
              maxSize: 8 * 1024 // 8kb
            }
          },
          generator: {
            filename: 'images/[name].[hash:5][ext]'
          }
        },
        // 打包html中的图片
        {
          test: /\.html$/,
          loader: "html-loader",
          options: {
            minimize: false,
            esModule: false,
          }
        },
        // 编译JS
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/, //排除本地需要编译的目录
          use: {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  "@babel/preset-env",
                  {
                    //按需转换JS
                    useBuiltIns: "usage",
                    // corejs 版本
                    corejs: 3,
                    targets: "defaults",
                  }
                ]
              ]
            }
          }
        }
      ]
    },
    plugins: [
      //打包HTML页面
      new HtmlWebpackPlugin({
        title: 'webpack5',
        template: './src/template/index.ejs',
        filename: 'index.html',
        meta: {
          keywords: '关键词'
        },
        // 压缩html页面 开发环境不需要
        // minify: {
        //   collapseWhitespace: true,
        //   keepClosingSlash: true,
        //   removeComments: true,
        //   removeRedundantAttributes: true,
        //   removeScriptTypeAttributes: true,
        //   removeStyleLinkTypeAttributes: true,
        //   useShortDoctype: true
        // }
      }),
      //提取CSS到单独的CSS文件
      new MiniCssExtractPlugin({
        filename: "style/[name].[hash:5].css",
      }),
      new StylelintPlugin({
        //指定检查源文件所在目录
        files: ["./src/style/*.(css|less)"]
      }),
      // 打包前 清理输出目录
      new CleanWebpackPlugin()
    ],
    devServer: {
      contentBase: resolve(__dirname, 'dist'),
      host: 'localhost',  // 配置启动ip地址
      port: 9090,  // 配置端口
      open: true, // 配置是否自动打开浏览器
      compress: true,
      liveReload: true, //热更新
      //配置代理 解决跨域
      proxy: {
        // http://localhost:8080/api
        "/api": {    // 这里的`/api`是自定义的
          // http://localhost:8080/api/users = >  https://api.github.com/api/users
          target: "https://api.github.com/", //这里是真实的接口baseURL
          //http://localhost:8080 => https://api.github.com
          changeOrigin: true,
          ws: true,
          secure: false,
          pathRewrite: {
            //去掉 '/api/'
            // http://localhost:8080/api/users = >  https://api.github.com/users
            "^/api": "", // 这里的`^/api`也是是自定义的
          },
        },
      }
    },
    target: 'web', //热更新
  }
  //生产环境的配置,需要额外的压缩功能
  if (env.production) {
    config.mode = "production",
      config.optimization = {
        minimize: true,   //优化CSS
        minimizer: [
          new CssMinimizerPlugin({
            parallel: true,  //使用多进程并发执行,提升构建速度
          }),
        ]
      },
      config.plugins = [
        //打包HTML页面
        new HtmlWebpackPlugin({
          title: 'webpack5',
          template: './src/template/index.ejs',
          filename: 'index.html',
          meta: {
            keywords: '关键词'
          },
          // 压缩html页面
          minify: {
            collapseWhitespace: true,
            keepClosingSlash: true,
            removeComments: true,
            removeRedundantAttributes: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true,
            useShortDoctype: true
          }
        }),
        //提取CSS到单独的CSS文件
        new MiniCssExtractPlugin({
          filename: "style/[name].[hash:5].css",
        }),
        new StylelintPlugin({
          //指定检查源文件所在目录
          files: ["./src/style/*.(css|less)"]
        }),
        // 打包前 清理输出目录
        new CleanWebpackPlugin(),
        // 图片压缩
        new ImageMinimizerPlugin({
          minimizerOptions: {
            // Lossless optimization with custom option
            // Feel free to experiment with options for better result for you
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              // Svgo configuration here https://github.com/svg/svgo#configuration
              // [
              //   "svgo",
              //   {
              //     plugins: extendDefaultPlugins([
              //       {
              //         name: "removeViewBox",
              //         active: false,
              //       },
              //       {
              //         name: "addAttributesToSVGElement",
              //         params: {
              //           attributes: [{ xmlns: "http://www.w3.org/2000/svg" }],
              //         },
              //       },
              //     ]),
              //   },
              // ],
            ],
          },
          filter: (source, sourcePath) => {
            if (source.byteLength < 8 * 1024) { //小于8Kb不优化
              return false;
            }
            return true;
          },
          loader: false,
        }),
      ]
  }
  return config;
}

package.json部分:

"devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.15.0",
    "autoprefixer": "^10.3.1",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^4.0.0-alpha.0",
    "core-js": "^3.16.1",
    "css-loader": "^6.2.0",
    "css-minimizer-webpack-plugin": "^3.0.2",
    "file-loader": "^6.2.0",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.2",
    "image-minimizer-webpack-plugin": "^2.2.0",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-jpegtran": "^7.0.0",
    "imagemin-optipng": "^8.0.0",
    "imagemin-svgo": "^9.0.0",
    "less-loader": "^10.0.1",
    "mini-css-extract-plugin": "^2.2.0",
    "postcss": "^8.3.6",
    "postcss-loader": "^6.1.1",
    "style-loader": "^3.2.1",
    "stylelint": "^13.13.1",
    "stylelint-config-standard": "^22.0.0",
    "stylelint-webpack-plugin": "^3.0.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.49.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2"
  },

采用了生产环境模式打包,报错如下:
webpack打包报错

  1. 图片压缩优化,怎么涉及到less?
  2. 报错乱码是中文怎么解决
  3. 看提示信息 “\node_modules\jpegtran-bin\vendor\jpegtran.exe” 和这个文件有关,实际上这个目录下面确实没有'jpegtran.exe'这个文件

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘香 2022-09-20 00:59:51

很简单的方法,下载 jpegtran.exe 丢到 node_modules\jpegtran-bin\vendor\

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文