a5hk
a5hk

Reputation: 7834

How to get field values from package.json using process.env

I want to access key/values set in package.json. I tried using process.env.npm_package_*. I was able to access some fields like process.env.npm_package_version and a few more but most of then are undefined. Reading this I think I should be able to access other fields.

A simplified version of my package.json:

{
  "name": "my-package-name",
  "version": "3.4.3",
  "homepage": "https://github.com/a5hk/repo",
  "type": "module",
  "scripts": {
    "example": "node ./dist/index.js",
  }
}

For example process.env.npm_package_homepage returns undefined. This is called inside /dist/index.js which I run it using example script.

UPDATE

The minimal example:

{
  "name": "ntest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "example": "node ./index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/a5hk/ntest.git"
  },
  "author": "a5hk",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/a5hk/ntest/issues"
  },
  "homepage": "https://github.com/a5hk/ntest#readme"
}
console.log(process.env.npm_package_version)
console.log(process.env.npm_package_homepage)
console.log(process.env)

The second console.log return undefined.

Upvotes: 0

Views: 2635

Answers (1)

Dimanoid
Dimanoid

Reputation: 7289

Just import json file

   const p = require('package.json');
   console.log('version:', p.version);
   console.log('repository type:', p.repository.type);

https://codesandbox.io/s/billowing-glade-sl5fql

Upvotes: 2

Related Questions