I am creating a React JS app. I have installed terser-webpack-plugin to both try to compress my code as well as remove console.log() statements. However, it does not seem to be working.
I have installed the terser-webpack-plugin as follows:
npm install terser-webpack-plugin --save-dev
My webpack.config.js file looks like this:
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' }
])
]
};
However, when I run npm run build or npm run dev it does not seem to have any effect on the final file size and the comments are still there. What am I doing wrong?
As a side note, I am wondering how to make sure this only works for build and does not remove the comments on dev.
Using
optimization: {
minimize: true,
tells webpack to create and use an instance of TerserPlugin with some default configuration options. Then you create another instance of the plugin:
new TerserPlugin({
It is better not to use minimize: true,
This configuration works:
...(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.
Note how the boolean flag isProduction is used in the above code snippet. The flag is defined as follows:
const isProduction = (env && env.prod) ? true : false;
To make the flag work you call webpack as webpack in dev and webpack --env.prod for production build.
For the reference, the above code snippet is taken from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With