Reputation: 73
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 ?
Upvotes: 0
Views: 1439
Reputation: 24992
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:
To install replace
you'll need to cd
to your project directory and run:
npm install replace --save-dev
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 (i.e. 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 (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.
To install cross-var
you'll need to cd
to your project directory and run:
npm install cross-var --save-dev
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"
}
}
Upvotes: 1