Npm script with npm_package_version
In the script section of my file, package.json
I am trying to rename some files in a directory, however I would like to enter a value on the command line that is taken from package.json
(version) itself.
So in the example build:rename
script below , I would like it to replace the token in the script ( somevalue
) before executing it.
In this case, I would like to pass in npm_package_version
so that it is part of the filename. I'm at a loss ...
"scripts": {
"build:copy": "mkdirp dist && cp src/*.js dist/",
"build:rename": "renamer --regex --find '(.+)(.js)' --replace '$1**somevalue**$2' dist/*"
}
source to share
The current version
referenced in package.json
can be referenced through a script using package.json vars like this:
bash
In bash shells using the syntax - (note the dollar prefix $
):
$npm_package_version
Window
In cmd.exe and Powershell using the syntax - (note the percent prefix and suffix %
):
%npm_package_version%
cross-patform
To achieve this cross-platform utlize cross-var :
$ npm i -D cross-var
build:rename
The script can be changed like this:
"scripts": {
...
"build:rename": "cross-var \"renamer --regex --find '\\.js$' --replace '$npm_package_version.js' dist/*\""
},
Note: additional change in a regular expression --find
like cross-var
, do not seem to look nice when the value --replace
includes the dollar link ( $1
, $2
) in the brackets of substring / group in parenthesis in the value --find
. The new regex simply matches the part of files / lines ending in .js
.
Example directory
The launch of the updated build:rename
script (as version
in package.json
there 0.3.0
), rename .js
files in the directory dist
from this:
.
├── dist
│ ├── a.html
│ ├── b.css
│ ├── foo.js
│ ├── bar.js
│ └── quux.js
... to that:
.
├── dist
│ ├── a.html
│ ├── b.css
│ ├── foo0.3.0.js
│ ├── bar0.3.0.js
│ └── quux0.3.0.js
Additional note
The cp command used in the build:copy
script will also not work cross-platform. This can be replaced with the copyfiles package :
$ npm i -D copyfiles
... and the build:copy
script is then replaced with the following:
"scripts": {
"build:copy": "copyfiles -u 1 \"src/*.js\" \"dist\"",
...
},
The part mkdirp dist &&
in your script then becomes redundant as copyfiles
with creating the necessary directory (i.e. dist
).
If cross platform is not needed for your use case, just leave the build:copy
script as it is and change your build:rename
script to:
"build:rename": "renamer --regex --find '\\.js$' --replace $npm_package_version'.js' dist/*"
source to share