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:
This is the simplest approach if your config doesn't change between environments:
- First, create a
config.jsonfile 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
publicfolder to thebuilddirectory. So if you placeconfig.jsoninsidepublic, it'll automatically show up in the root of yourbuildfolder after runningnpm run build. - If you want to keep the file in your project root (not
public), add apostbuildscript to yourpackage.jsonto copy it over:
"scripts": { "start": "react-scripts start", "build": "react-scripts build", "postbuild": "cp config.json build/config.json" }
Heads up: On Windows, replace
cpwithcopy. For cross-platform compatibility, installcpy-cli(npm install cpy-cli --save-dev) and use this script instead:"postbuild": "cpy config.json build/"
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:
- Create a
generate-config.jsfile 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) );
- Update your
package.jsonscripts 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.
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.jsonfile correctly without blocking it.
内容的提问来源于stack exchange,提问作者Hamid Sarani

