Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject a build number with webpack?

Tags:

webpack

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?

like image 225
David Wolever Avatar asked Jul 09 '14 20:07

David Wolever


People also ask

How do I bundle a JavaScript file using webpack?

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.

Does webpack Minifies the code?

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.

How does webpack DefinePlugin work?

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.

What is webpack DefinePlugin?

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.


2 Answers

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__); 
like image 148
newtriks Avatar answered Sep 18 '22 13:09

newtriks


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

like image 30
l2aelba Avatar answered Sep 16 '22 13:09

l2aelba