You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更优雅地访问package.json配置中的数组数据?

Better Ways to Access Array Values from package.json config

Great question! I’ve definitely struggled with this exact limitation of npm’s config environment variable flattening before. As you noticed, npm automatically flattens nested config values—turning arrays into numbered keys like npm_package_config_words_0—which is pretty clunky to work with. Here are a few cleaner approaches:


1. Parse a JSON string from your config

The simplest workaround without extra tools is to store your array as a JSON string directly in package.json, then parse it in your code. This keeps everything contained in your package.json config section.

Example:

Update your package.json config to quote the array as a JSON string (make sure to escape inner double quotes):

{
  "name": "who-rules-app",
  "config": {
    "foo": "bar",
    "words": "[\"tpr\", \"rules\"]"
  },
  "scripts": {
    "start": "node src/index.js"
  }
}

Then in your code, parse the string back into an array:

const words = JSON.parse(process.env.npm_package_config_words);
console.log(words); // Output: ["tpr", "rules"]

2. Fetch the full config via npm config get

npm has a built-in command to retrieve the full config value (including arrays) as JSON. You can run this command from your code using Node’s child_process module to get the array directly.

Example:

const { execSync } = require('child_process');

try {
  // Use npm's built-in command to get the full config value
  const rawWords = execSync('npm config get package:config:words', { encoding: 'utf8' });
  const words = JSON.parse(rawWords);
  console.log(words); // Output: ["tpr", "rules"]
} catch (error) {
  console.error('Failed to load config:', error);
}

This preserves the native array format in your package.json but requires a child process call.


3. Preload config into a custom environment variable

If you want to avoid child processes and keep your package.json config clean, create a pre-start script that reads your package.json directly, extracts the config, and injects it into a single environment variable as JSON.

Example:

  1. Create a scripts/load-config.js file:
const fs = require('fs');
const path = require('path');

// Read and parse package.json
const packageJson = JSON.parse(
  fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')
);

// Inject the full config object as a JSON string into an environment variable
process.env.APP_CONFIG = JSON.stringify(packageJson.config);
  1. Update your package.json scripts to run this before starting your app:
{
  "name": "who-rules-app",
  "config": {
    "foo": "bar",
    "words": ["tpr", "rules"]
  },
  "scripts": {
    "prestart": "node ./scripts/load-config.js",
    "start": "node src/index.js"
  }
}
  1. Access the array in your code:
const appConfig = JSON.parse(process.env.APP_CONFIG);
console.log(appConfig.words); // Output: ["tpr", "rules"]

4. Switch to a dedicated config file (optional)

If you find npm’s config system too limiting, consider moving your configuration to a dedicated file like config.json or using a tool like dotenv for environment-based config. This gives you full control over nested structures and arrays without workarounds.


Which one to choose?

  • Use Option 1 for quick, no-fuss setup if you don’t mind storing the array as a string.
  • Use Option 3 if you want to keep native array syntax in package.json and avoid child processes.
  • Use Option 2 if you prefer using npm’s built-in tools without custom scripts.

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:09:41