How can I inject a build number with 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?


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


There is a plugin to auto inject version from package.json. It can inject it into HTML, CSS, JS as a comment, but also as a value by special tag webpack-auto-inject-version.

How to:

First of all, you have to add it to your project:

npm i webpack-auto-inject-version

Then you need to set up your webpack config:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
    plugins: [
        new WebpackAutoInject()
    ]
}

As you want to inject it into javascript, you should add a tag inside your javascript file ( which will be changed to version during the webpack compilation )

var version = '[AIV]{version}[/AIV]';
console.log(version);

Auto increasing:

You can set it up to auto increase the version directly from webpack by:

webpack --other-webpack-settings --major

webpack --other-webpack-settings -- minor

webpack --other-webpack-settings --patch

Where --other-webpack-settings is equal to your custom line args. Simplifying - you need to att --major, --minor or --patch whenever you want to auto increase a version.