Dynamically add version number to dest output files w/ grunt

adam picture adam · Dec 7, 2013 · Viewed 23.4k times · Source

I have a package.json file with our version number, such as:

{
    name: "myproject"
    version: "2.0"
}

My goal is to dynamically add the version number from the package.json file into the output files. For example, in the javascript I don't want to manually update the version number, but would like something similar to this to be generated after each grunt build:

/* My Project, v2.0 */
window.myProject = {
    version: "2.0"
};

Is there an easy way to do this in my Gruntfile.js configuration?

Answer

adam picture adam · Dec 7, 2013

I implemented: https://github.com/erickrdch/grunt-string-replace

In my source css/js files, I use the text {{ VERSION }} which gets replaced with the version number set in the package.json file. Below is the config I added to Gruntfile.js.

'string-replace': {
  version: {
    files: {
      // the files I did string replacement on
    },
    options: {
      replacements: [{
        pattern: /{{ VERSION }}/g,
        replacement: '<%= pkg.version %>'
      }]
    }
  }
},
pkg: grunt.file.readJSON('package.json'),