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

Create React App构建后能否生成根目录JSON配置文件用于应用配置?

Absolutely! You can totally set up a JSON config file in your project's root (and have it included in the final build directory) for handling translations, API URLs, and other environment-specific settings with Create React App. Let's break down the best approaches to make this work:

1. Manual Config File + Ensure It's Included in Build

This is the simplest approach if your config doesn't change between environments:

  • First, create a config.json file in your project root with your desired settings:
{
  "apiUrls": {
    "auth": "/api/auth",
    "products": "/api/products"
  },
  "translation": {
    "defaultLocale": "en",
    "supportedLocales": ["en", "fr", "es"]
  }
}
  • By default, CRA copies everything in the public folder to the build directory. So if you place config.json inside public, it'll automatically show up in the root of your build folder after running npm run build.
  • If you want to keep the file in your project root (not public), add a postbuild script to your package.json to copy it over:
"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "postbuild": "cp config.json build/config.json"
}

Heads up: On Windows, replace cp with copy. For cross-platform compatibility, install cpy-cli (npm install cpy-cli --save-dev) and use this script instead:
"postbuild": "cpy config.json build/"

2. Dynamically Generate Config (For Multi-Environment Setups)

If you need different config values for development, staging, or production, use a Node.js script to generate the file dynamically based on environment variables:

  1. Create a generate-config.js file in your project root:
const fs = require('fs');
const path = require('path');

// Pull values from environment variables, or use defaults
const config = {
  apiUrls: {
    auth: process.env.REACT_APP_AUTH_API || '/api/auth',
    products: process.env.REACT_APP_PRODUCTS_API || '/api/products'
  },
  translation: {
    defaultLocale: process.env.REACT_APP_DEFAULT_LOCALE || 'en',
    supportedLocales: ['en', 'fr', 'es']
  }
};

// Write the config to public folder so CRA copies it to build
fs.writeFileSync(
  path.join(__dirname, 'public/config.json'),
  JSON.stringify(config, null, 2)
);
  1. Update your package.json scripts to run this before building:
"scripts": {
  "prebuild": "node generate-config.js",
  "build": "react-scripts build",
  "start": "react-scripts start"
}

Now every time you run npm run build, the script will generate a fresh config.json using your environment variables (or defaults) and it'll end up in your build directory.

3. Read the Config File in Your React App

Once the config file is in your build directory, you can fetch it when your app initializes:

// src/config.js
export const loadConfig = async () => {
  try {
    const response = await fetch('/config.json');
    const config = await response.json();
    return config;
  } catch (error) {
    console.error('Failed to load config:', error);
    // Fallback to default config if the file can't be loaded
    return {
      apiUrls: { auth: '/api/auth', products: '/api/products' },
      translation: { defaultLocale: 'en', supportedLocales: ['en'] }
    };
  }
};

Then use it in your main App component:

// src/App.js
import { useEffect, useState } from 'react';
import { loadConfig } from './config';

function App() {
  const [config, setConfig] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchAppConfig = async () => {
      const configData = await loadConfig();
      setConfig(configData);
      setIsLoading(false);
    };
    fetchAppConfig();
  }, []);

  if (isLoading) return <div>Loading app settings...</div>;

  return (
    <div className="App">
      <h2>Default Locale: {config.translation.defaultLocale}</h2>
      <p>Auth API URL: {config.apiUrls.auth}</p>
    </div>
  );
}

export default App;

Important Notes

  • Never put sensitive data (like API keys or secrets) in this JSON file—it's publicly accessible to anyone visiting your app. Use environment variables prefixed with REACT_APP_ for sensitive values, or fetch them from a secure backend endpoint.
  • Make sure your hosting server (like Nginx, Netlify, etc.) serves the config.json file correctly without blocking it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:00:51