I'd like to inject a build number and version information to my project as it's built with webpack. For example, so that my code can do something like:
var buildInfo = require("build-info");
What would be the best way to generate that build-info
module at build time?
You can bundle your JavaScript using the CLI command by providing an entry file and output path. Webpack will automatically resolve all dependencies from import and require and bundle them into a single output together with your app's script.
Since webpack 4, the production output gets minified using terser by default. Terser is an ES2015+ compatible JavaScript-minifier. Compared to UglifyJS, the earlier standard for many projects, it's a future-oriented option.
The DefinePlugin replaces variables in your code with other values or expressions at compile time. This can be useful for allowing different behavior between development builds and production builds.
Oct 29, 2021. Webpack's DefinePlugin() function lets you replace a given token in the compiled code with another token. A common use case is using it to define environment variables when you cannot use an . env file directly.
You can use the DefinePlugin that will make your build info available inlined with your code:
Config
new webpack.DefinePlugin({ __VERSION__: JSON.stringify('12345') })
App code
console.log(__VERSION__);
I would do more simpler, just use npm version patch
(npm-version) (no plugin required)
package.json (Example path version before building)
{ "version": "1.0.0", "scripts": { "build": "npm version patch && node build/build.js" } }
So when you run npm run build
this will patch the version (1.0.0
to 1.0.1
in your package.json)
Bonus: You can also add this to your config (example config/prod.env.js
)
'use strict' const pkg = require('./package.json') module.exports = { NODE_ENV: '"production"', VERSION: pkg.version }
Then you can use process.env.VERSION
anywhere in your our JS
Updated: Or just use process.env.npm_package_version
without required to include package.json
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