简体   繁体   中英

Good way of getting version from package.json

I am developing a sdk that will be available on npm.

The sdk should be able to deliver its version to the client. I would like this version to be the same as the package.json version.

But when in my sdk I put import {version} from '../package.json' , I see that ALL package.json is added to the build.

Is there a good way of getting the version or will I be forced to set the version variable in my sdk with something like a bash script on npm version ? Or how would you do this ?

If you are using nodejs, I think you could save your environment and your app-version in an independent environment file. For example, I save my setting on a file named .env and read them by using an npm module called dotenv

You can achieve this by specifying 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:

  1. To install replace you'll need to cd to your project directory and run:

     npm install replace --save-dev 
  2. Then add the following to the scripts section of to your package.json :

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

Running:

When you run the following command via your CLI to publish your package:

$ npm publish

the prepublishOny script (which is a pre hook ) will be invoked which in turn will invoke the add-version script.

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


Cross Platform

The to string in the add-version script (above) currently uses the $ prefix (ie $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 .

  1. To install cross-var you'll need to cd to your project directory and run:

     npm install cross-var --save-dev 
  2. Then redefine the add-version script as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM