How to preserve dedicated comment with Webpack's Terser?

169 Views Asked by At

I want do preserve dedicated comments which contain delimiters for Thymeleaf's processing engine. When Thymeleaf finds these delimiters inside comments, it will parse the content, remove the comment signs and delete everything after that until the next JS instruction (in the following example the empty quotes "" would therefore get removed as well). This way it is possible to have valid JS for e.g. pre-processing with Webpack.

An example looks like that:

const errorMessage = /*[[#{registration-ldap.error.message}]]*/ "";

Now in certain conditions these delimiters might cause conflicts, e.g. in some RegExp, so you want to tell Thymeleaf not to parse certain blocks. For that you can embrace the sequence like that:

/*[# th:inline="none"]*/
_PHONE_REGEX = new RegExp("^[+]*[(]?\\d{1,4}[)]?[-\\s\./\\d]*$");
/*[/]*/

So what I want is to preserve all the comments which have Thymeleaf delimiters inside. Therefore I added this configuration to Webpack:

const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");

let babelConfig = {
    test: /\.js$/i,
    exclude: /node_modules/,
    use: {
        loader: "babel-loader",
        options: {
            presets: ["@babel/preset-env"]
        },
    }
};

let config = {
    entry: {
        scripts: path.resolve(__dirname, "src/main/resources/static/source/js/scripts-bundle-entry.js")
    },
    output: {
        filename: "./js/famous-[name].js",
        path: path.resolve(__dirname, "src/main/resources/static/build")
    },
    mode: "production",
    watch: true,
    module: {
        rules: [
            babelConfig
        ]
    },
    optimization: {
        splitChunks: { chunks: "all" },
        minimize: true,
        minimizer: [
            new TerserPlugin({
                     terserOptions: {
                         /* Preserve Thymeleaf delimiters inside JS comments. */
                         format: { comments: /^\[/ }
                     }
            })
        ]
    },
    plugins: []
}

module.exports = config;

The problem is: When the block which got surrounded by comments I want to preserve is located last in a file (no matter if it's only one file or a modular configuration), then the last comment gets deleted.

So the output of the example above, assumed these 3 lines of code are the only ones in the only file, looks like that:

/*[# th:inline="none"]*/
_PHONE_REGEX=new RegExp("^[+]*[(]?\\d{1,4}[)]?[-\\s./\\d]*$");

As you can see, the comment containing Thymeleaf's closing instruction is missing.

What can I do to preserve comments which are located at the end of a file?

Edit:

Well, it doesn't seem to make any difference whether you declare your own comments to preserve or trying to keep built-in preserved comments like @license. They all get removed as soon as they are located at the end of a JS file.

0

There are 0 best solutions below