If you want to insert a placeholder text string into your JavaScript file, you can do so by defining it within the code. Assume we have a file called build.js
with a variable named VERSION
set like this:
// build.js
const VERSION = '@VERSION@'
In this case, the placeholder text string is marked as @VERSION@
.
To implement this, you can use the package replace in an npm-script following these steps:
To start, install the replace
package by navigating to your project folder and running the command:
npm install replace --save-dev
Next, add the below configuration in the scripts
section of your package.json
:
{
...
"version": "1.0.0",
"scripts": {
"add-version": "replace -s \"@VERSION@\" $npm_package_version build/build.js",
"prepublishOnly": "npm run add-version"
}
}
Execution:
When using the terminal to publish your package with the command:
$ npm publish
The prepublishOny
script (which serves as a pre hook) will be triggered, then executing the add-version
script.
This action replaces @VERSION@
with the package version (e.g., 1.0.0
) in the build.js
file. This method secures the npm package version within the generated file.
Cross Platform Compatibility
The to parameter in the add-version
script mentioned above gestures to the bash shell environment due to the $
sign usage (i.e., $npm_package_version
). To ensure cross-platform functionality, consider employing cross-var.
To get started, install cross-var
by going to your project directory and executing the command:
npm install cross-var --save-dev
Afterward, adjust 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"
}
}