I use TerserWebpackPlugin
with comments: true
. But Terser removes comments after useful code - at the end of file. I would like to avoid this behavior.
console.log('Example2');
// any comments will be removed from here
/* myComment after */
// myComment after
How to do it?
Maybe do I need to use RegExp or callback to avoid it? But it will be difficult to support:
comments?: boolean | 'all' | 'some' | RegExp | ( (node: any, comment: {
value: string,
type: 'comment1' | 'comment2' | 'comment3' | 'comment4',
pos: number,
line: number,
col: number,
}) => boolean );
Please run build:dev
or build:prod
.
File structure
src/index.html
src/js/index.js
src/scss/styles.scss
(empty)package.json
webpack.config.js
src/js/index.js
/* myComment before */
// myComment before
console.log('Example');
// myComment center
/* myComment center */
console.log('Example2');
// any comments will be removed from here
/* myComment after */
// myComment after
package.json
{
"name": "terser-prod-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build:dev": "webpack --mode development",
"build:prod": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.6.1",
"sass": "^1.53.0",
"sass-loader": "^13.0.2",
"terser-webpack-plugin": "^5.3.3",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
}
}
webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const config = {
entry: ["./src/js/index.js"],
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
},
devtool: false,
// mode: "production",
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
format: {
// false - remove
comments: true,
beautify: true,
},
},
extractComments: false,
}),
// '...', // works only after TerserPlugin
],
},
module: {
rules: [
{
test: /\.(sass|scss)$/,
include: path.resolve(__dirname, "src/scss"),
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {},
},
{
loader: "css-loader",
options: {
sourceMap: true,
url: false,
},
},
{
loader: "sass-loader",
options: {
implementation: require("sass"),
sourceMap: true,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "styles.css",
}),
],
};
module.exports = (env, argv) => {
return config;
};
HTML
<!DOCTYPE html>
<html>
<head></head>
<body></body>
</html>