Reputation: 10911
My package.json file includes a version for my module, which ultimately get's compiled into an app.bundle.js file that I include in my web project. I would REALLY like to have the version number from the package.json file written to the app.bundle.js file as a comment right at the beginning of the file.
Is there a WebPack plugin to do this or a setting with WebPack itself?
Upvotes: 29
Views: 24575
Reputation: 9163
In Webpack 5, TerserPlugin
is included "out of the box" (i.e. no need to install another plugin).
I've had a good experience using something like the following:
optimization: {
minimizer: [new TerserPlugin({
terserOptions: {
format: {
preamble: `/* Copyright ${new Date().getUTCFullYear()}, XYZ Corp. ${require('./package.json').name} ${require('./package.json').version} (${new Date().toUTCString()}) */`
}
}
})],
}
The above will result in the following being prefixed onto your bundle:
/* Copyright 2022, XYZ Corp. package-name 1.0.0 (Thu, 05 May 2022 20:03:36 GMT) */
Upvotes: 5
Reputation: 13818
Webpack comes with a BannerPlugin that adds a banner to the top of each generated chunk.
You can require your package.json
and use it as any regular JavaScript object to get the version
field.
var PACKAGE = require('./package.json');
var version = PACKAGE.version;
Then use it to generate the desired banner string that will be used in the BannerPlugin
.
var PACKAGE = require('./package.json');
var banner = PACKAGE.name + ' - ' + PACKAGE.version;
module.exports = {
// Other stuff
plugins: [
new webpack.BannerPlugin(banner)
]
};
I have used it to add the version from the package.json
file and other info to the top of a library of my own. Check the webpack.config.js of this project for a working example.
Upvotes: 47