javascript - 插件无法在带有 React JS 的 Webpack 中工作

标签 javascript reactjs webpack plugins

我正在创建一个 React JS 应用程序。我已经安装了 terser-webpack-plugin 来尝试压缩我的代码并删除 console.log() 语句。但是,它似乎不起作用。

我已经安装了 terser-webpack-plugin,如下所示:

npm install terser-webpack-plugin --save-dev

我的 webpack.config.js 文件如下所示:

const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            plugins: [
                "@babel/plugin-syntax-dynamic-import"
            ]
          }
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      }
    ]
  },
  optimization: {
    minimize: true,
    minimizer: [
        new TerserPlugin({
                terserOptions: {
                        extractComments: 'all',
                        compress: {
                                drop_console: true
                        },

                }
        })
    ],
  },
  devtool: 'eval-source-map',
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    }),
    new CopyPlugin([
      { from: 'src/css', to: 'css' }
    ])
  ]
};

但是,当我运行 npm run buildnpm run dev 时,它似乎对最终文件大小没有任何影响,并且注释仍然存在。我做错了什么?

作为旁注,我想知道如何确保这仅适用于构建并且不会删除开发上的评论。

最佳答案

使用

optimization: {
    minimize: true,

告诉 webpack 创建并使用 TerserPlugin 的实例以及一些默认配置选项。然后创建该插件的另一个实例:

new TerserPlugin({

最好不要使用minimize: true,

此配置有效:

...(isProduction && {
        minimizer: [
          new TerserPlugin({
            cache: false,
            parallel: true,
            sourceMap: false,     // set to true if debugging of production build needed
            terserOptions: {
              keep_classnames: false,
              mangle: true,
              compress: false,
              keep_fnames: false,
              output: {
                comments: false,
              }
            }
          })
        ]
      }),

I am wondering how to make sure this only works for build and does not remove the comments on dev.

请注意上面的代码片段中如何使用 bool 标志 isProduction。该标志定义如下:

const isProduction = (env && env.prod) ? true : false;

要使该标志发挥作用,您可以在开发中将 webpack 称为 webpack ,并在生产构建中将其称为 webpack --env.prod

供引用,以上代码片段摘自here

关于javascript - 插件无法在带有 React JS 的 Webpack 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57829566/

相关文章:

javascript - 如何避免在简单的类名更改时重新渲染整棵树?

javascript - 如何将数据传递给 props.children?

reactjs - 将 React 开发工具与 Preact 结合使用

JavaScript:如果检测到碰撞则更改对象路径

javascript - 使用正则表达式从日期和时间获取时间

javascript - 如何检查一个数组中的某个项是否存在于另一个数组中?

javascript - 何时根据来自 redux 的数据更新本地 react 状态?

json - 在 React 组件中导入 Json 文件

javascript - "jQuery requires a window with a document"webpack 2错误

javascript - Js追加和删除特定的div