Search code examples
npmpackage.jsonnpm-scripts

How can I reference package version in npm script?


I want to reference my package version in a npm script so I can show current version in the app. Something like

{
  "name": "bla",
  "version": "1.0.0",
  "author": "bla bla",
  "scripts": {
    "build": "node VERSION=<<package.version>> build/build.js"
  }
}

Is there a way to do this?


Solution

  • 1) Referencing package version in npm-scripts.

    In npm-script's you can reference the version using the variable npm_package_version. For example:

    • Using a bash shell (E.g. Linux, macOS):

      {
        ...
        "version": "1.0.0",
        "scripts": {
          "build": "echo $npm_package_version"
        }
      }
      

      Note the $ prefix

    • Using Windows (E.g. cmd.exe, Powershell):

      {
        ...
        "version": "1.0.0",
        "scripts": {
          "build": "echo %npm_package_version%"
        }
      }
      

      Note the % prefix and suffix

    • Cross platform

      To utilize one syntax cross-platform check out the package cross-var


    2) Referencing package version in node script.

    The package version can also be referenced in your a app/node script (i.e. build.js) as follows:

    const VERSION = process.env.npm_package_version;
    console.log(VERSION); // --> 1.0.0
    

    3) Replacing a placeholder string in a .js file with package version.

    Another way to achieve this is to specify a placeholder text string within your JavaScript file. Lets say we have a file named build.js and within that file we have a variable named VERSION declared as follows:

    // build.js
    const VERSION = '@VERSION@'
    

    As you can see, the placeholder text string is @VERSION@.

    You can then install and utilize the package called replace in an npm-script as follows:

    {
      ...
      "version": "1.0.0",
      "scripts": {
        "add-version":  "replace -s \"@VERSION@\" $npm_package_version build/build.js"
      }
    }
    

    Running npm run add-version will replace the instance of @VERSION@ with the package version (i.e. 1.0.0), in the file named build.js. This solution will hard-code the npm package version into the resultant file.

    Note: The to string in the add-version script (above) currently uses the $ prefix (i.e. $npm_package_version) to access the variable, so this will only run successfully on a bash shell. However, for cross-platform usage you'll need to use cross-var as explained in section one (above). In which case the add-version script can be defined as follows:

    {
      ...
      "version": "1.0.0",
      "scripts": {
        "add-version":  "cross-var replace -s \"@VERSION@\" $npm_package_version build/build.js"
      }
    }