0

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.

12
  • npm v7? because nothing else comes to my mind.. Commented Jan 13, 2022 at 20:31
  • @traynor npm version 8.3.0 Commented Jan 13, 2022 at 21:02
  • well, or v8, then. I'd say it's something with version+OS combination, especially if it can't read only vars with special characters.. Commented Jan 13, 2022 at 21:09
  • I am using wsl (Ubuntu), I also tried Ubuntu on a VM, same results. I will try some other distro as well Commented Jan 13, 2022 at 21:16
  • 1
    github.com/npm/cli/issues/2609 and github.com/npm/rfcs/blob/main/implemented/… Commented Jan 13, 2022 at 22:11

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I had to write require('./package.json') to get this to work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.