简体   繁体   中英

package.json - is it possible to use version as a variable in script

Every time I compress my project, I need to manually sync version with the generated file name like CCCC007.tgz
In my package.json, compress-files script like below:

{
  "name": "MyBuild",
  "version": "0.0.7",
  "scripts": {
    "dev": "nodemon --legacy-watch ./src",
    "start": "node src/",
    "compress-files": "tar --exclude='./node_modules' --exclude='./myBuild.pem' --exclude='./config/local.json' -zcvf ~/CCCC007.tgz . ",
  },
}

I am wondering whether I can make the version as variable and use it in the script compress-files with something like:

  "name": "MyBuild",
  "version": "0.0.7",
  "scripts": {
    "dev": "nodemon --legacy-watch ./src",
    "start": "node src/",
    "compress-files": "tar --exclude='./node_modules' --exclude='./myBuild.pem' --exclude='./config/local.json' -zcvf ~/CCCC${this.version}.tgz . ",
  },

You can't refer to another object in JSON, and certainly not inside a value.

From the / direction, it looks like you're on linux. You can probaly do something like this:

"get-version": "node -e \"console.log(require('./package.json').version)\"",
"compress-files": "tar [...] `npm run get-version`",

That being said, there are tools to releases and versioning that should make life easier. You could give Release-It a try. But...if a package.json script with tar is all you need, don't let anyone tell you that you should be doing it a different way.

As far as I know, you can use this variables inside the package.json:

${npm_package_name} ${npm_package_version}

Readed from this post

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