How can I remove comments inside the HTML files when I do Webpack production build?
After I do the production build in Webpack, I would like to have the html file with no comments.
The current solution of using TerserPlugin/UglifyJsPlugin works for JavaScript files only?
I use the following regex test: /\.html(\?.*)?$/i,
but it still doesn't work.
The command I run is $ npm run production
The scripts section from the package.json file:
"scripts": {
"production": "webpack --optimize-minimize --config production.config.js",
},
The Webpack production config file - production.config.js.
The below doesn't remove HTML comments
module: {
rules: [
{
test: /\.css$/,
use: [
// style-loader
{
loader: 'style-loader'
},
// css-loader
{
loader: 'css-loader',
options: {
modules: true
}
},
// sass-loader
{
loader: 'sass-loader'
}]
},
{
test: /\.html$/i,
use: ['file-loader?name=[name].[ext]', 'extract-loader', 'html-loader']
// use: [{
// loader: ['html-loader'],
// options: {
// minimize: true
// }
// }]
}
]
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
// https://github.com/webpack-contrib/terser-webpack-plugin#terseroption
test: /\.html(\?.*)?$/i,
//
// https://webpack.js.org/plugins/terser-webpack-plugin/#remove-comments
terserOptions: {
output: {
comments: false,
},
},
extractComments: false,
}),
],
},
To remove comments in HTML in production mode, you need the plugin, HtmlWebpackPlugin.
In its minify
option put removeComments: true
, or do it like with my isProd
flag:
plugins: [
new HTMLWebpackPlugin({
template: './index.html',
inject: 'body',
minify: {
collapseWhitespace: isProd,
removeComments: isProd
}
}),
]
const isDev = process.env.NODE_ENV === 'development';
const isProd = !isDev;
const optimization = () => {
const config = {
splitChunks: {
chunks: 'all'
}
};
if (isProd){
config.minimizer = [
new OptimizeCssAssetWebpackPlugin(),
new TerserWebpackPlugin({
terserOptions: {
output: {
comments: false,
},
},
}),
]
}
return config;
};
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