Home > OS >  How do I properly pass a variable in npm?
How do I properly pass a variable in npm?

Time:07-20

I am trying to pass a variable in npm per Solution 1 here How to use npm config variables of package.json in npm scripts but cannot seem to get it right. I have tried several variations of the below code to no avail. Can someone tell me the right way to do it?

UPDATE:

I had actually started from a point closer to that mentioned by xehpuk (below) but I cannot retrieve the variable from there either. I have updated the code below to reflect that

SOLUTION: This works!

test.js

const main = function () {
  console.log(process.argv)
}

main()

package.json

{
  "name": "test",
  "version": "0.1.0",
  "description": "testing",
  "dependencies": {
  },
  "config": {
    "params": "{\"height\": 33, \"width\": 22}]"
  },
  "license": "",
  "scripts": {
  "return": "node test.js --params=$npm_package_config_params"  
  }
}

result

[
  '/home/dcode/.nvm/versions/node/v18.3.0/bin/node',
  '/mnt/d/bin/tools/test.js',
  '--params={"height":',
  '33,',
  '"width":',
  '22}]'
]

CodePudding user response:

A working solution is posted above!

CodePudding user response:

You can access it via process.env.npm_package_config_params.

package.json > config | npm Docs

process.argv works for me with:

{
    "config": {
      "params": "{\"height\": 33, \"width\": 22}]"
    },
    "scripts": {
      "return": "node test.js \"$npm_package_config_params\""
    }
}

Result:

$ npm run return

> [email protected] return
> node test.js "$npm_package_config_params"

[
  '/usr/bin/node',
  '/home/xehpuk/test.js',
  '{"height": 33, "width": 22}]'
]
  • Related