When I use the Webpack BannerPlugin, it adds a comment to the top of the output file, but the comment just says to check another file.
Is there a way using the BannerPlugin or another webpack tool I can insert the version number in the output file itself?
Current Output file:
/*! For license information please see main.js.LICENSE.txt */
(()=>{console.log("myjs");})();
Need:
/*! Current main.js Version: 1.0.0 */
(()=>{console.log("myjs");})();
My webpack config:
let config = {
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
};
let mainConfig = {
...config,
entry: {
main: "./src/index.ts",
},
output: {
filename: "[name].js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new webpack.BannerPlugin({
banner: "Current main.js Version: " + PACKAGE.version + " */",
})
],
};
module.exports = [mainConfig];
I was able to resolve this issue by following this answer: https://stackoverflow.com/a/65650316/4871331
In summary: Webpack v5 and up automatically comes with the TerserWebpackPlugin, which optimizes the code. By default it will extract comments into a separate file (including the banner comment).
To get around this, you need to customize the terser to not extract comments.
First, install the plugin:
npm install --save-dev terser-webpack-plugin
Then add the configuration to webpack.config.js:
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
//...
optimization: {
minimizer: [new TerserPlugin({
extractComments: false,
})],
},
//...
};
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