npm command-line interface to inject version number into file

Viewed 766

Is there any CLI I can use with an npm script to inject my package.json version into some arbitrary file? I don't want to use gulp or grunt or webpack, etc.

1 Answers

This can be done in three parts.

It turns out the NPM puts the package version in an environment variable named npm_package_version when running scripts.

There is an NPM package called replace-in-file that provides a CLI for replacing strings.

Unfortunately the format for environment variable replacement on Windows (e.g. %FOO_BAR%) isn't the same as on Linux (e.g. $FOO_BAR). Luckily there is another NPM package called cross-var that makes environment variables consistent across platforms.

Put them together and you can replace e.g. x.x.x-SNAPSHOT with the current package version in all .example files in the dist directory using the following script in package.json:

scripts: {
  "build:insert-version": "cross-var replace-in-file \"x.x.x-SNAPSHOT\" \"$npm_package_version\" \"dist/*.example\""
}
Related