How to get the version of a module from its package.json

node.js < 12

VERSION=$(node -p "require('some-module/package.json').version")

node.js 12+

In Node.js 12+ you can no longer get the version of a module dependency with the version property unless the path is explicitly exported in the module with:

{
  "exports": {
    "./package.json": "./package.json"
  }
}

What you can do instead, is to use a regular expression to parse the version from you own package.json dependency property with:

VERSION=$(node -p "/(\d+\.\d+(?:\.\d+)?)/.exec(require('./package.json').dependencies.some-module)[1]") 

package.json example

The following npm script example copies the some-module from the ./node_modules folder to ./../some-module/1.7.3 outside the node_modules folder (note: adapt the regular expression, if the version of the some-module dependency contains other characters than numbers and the full stop):

{
  "dependencies": {
    "some-module": "1.7.3"
  },
  "devDependencies": {
    "copyfiles": "2.4.1"
  },
  "scripts": {
    "some-module:copy": "VERSION=$(node -p \"/(\\d+\\.\\d+(?:\\.\\d+)?)/.exec(require('./package.json').dependencies.some-module)[1]\") && copyfiles -u 3 \"node_modules/some-module/**/*\" some-module/$VERSION"
  }
}

Leave a comment

Your email address will not be published. Required fields are marked *