【问题标题】:How to get field values from package.json using process.env如何使用 process.env 从 package.json 获取字段值
【发布时间】:2022-08-19 19:59:14
【问题描述】:

我想访问在package.json 中设置的键/值。我尝试使用process.env.npm_package_*。我能够访问一些字段,例如process.env.npm_package_version 和更多字段,但其中大部分是undefined。阅读this 我想我应该能够访问其他领域。

我的package.json 的简化版:

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

例如process.env.npm_package_homepage 返回undefined。这在/dist/index.js 内部调用,我使用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)

第二个console.log 返回undefined

  • npm v7?因为我脑子里什么都没有。。
  • @traynor npm 版本 8.3.0
  • 好吧,或者v8,然后。我会说这是版本+操作系统组合的东西,特别是如果它不能只读取带有特殊字符的变量..
  • 我正在使用wsl(Ubuntu),我还在VM上尝试了Ubuntu,结果相同。我也会尝试其他发行版

标签: node.js npm npm-scripts


【解决方案1】:

只需导入json文件

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2018-01-01
    相关资源
    最近更新 更多