1

so I have an npm script where I start up a server and need to build to a directory in my project. The directory has a sub-directory that matches the version of my app that is defined in the package.json.

{
  name: “my-app”,
  version: “0.3.2”
  …
  scripts: {
    “server”: “npm-watch build:local & serve -C -l 5000 build/*”
  }
}

So instead of the asterisk I need it to replace that with the value I have for the version.

jrock2004
  • 3,229
  • 5
  • 40
  • 73
  • Reference the `npm_package_version` environment variable - as explained in my answer [here](https://stackoverflow.com/questions/48609931/how-can-i-reference-package-version-in-npm-script/48619640#48619640). Essentially running on _*nix_ you can redefine your npm script as: `"server": "npm-watch build:local & serve -C -l 5000 build/$npm_package_version"` – RobC Aug 07 '21 at 12:47

1 Answers1

0

I think it would be easier to write another starting file and read the version inside package.json

I have come out another solution by writing a start.sh.

folder structure
- my-project
   |- build
     |- 0.0.1
     |- 0.1.0
     |- 0.1.1
       |- index.js
   |-start.sh
   |-package.json

my start.sh

#!/bin/bash

export p="./build/$(ls ./build | sort -r | head -n 1)"
node $p

My solution is quite simple, list all the directory under ./build and then sort in reverse. Now 0.1.1 is the biggest version and it would list at first. head -n 1 means get the first line which is the current biggest version number.
Then use the dir as the node execution path.

Inside the package.json

"scripts": {
  "test": "bash start.sh"
}

I think it is similar way to change to your own command.

Note I have tried to put script content inside package.json, but the npm run would not interpret shell variables well. So I recommend write a standalone script.

鄭元傑
  • 1,417
  • 1
  • 15
  • 30