I want a Config File (JSON) in root folder after build to config my app.
like Translation and API Urls and ...
Can I do this with create react app?
Create config.js or json file outside src directory and include it in index.html like
<script src="%PUBLIC_URL%/config.js" type="text/javascript"></script>
configure parameters in config.js
var BASE_URL = "http://YOUR-URL";
you can get paramenters like
const BASE_URL = window.BASE_URL;
config.js is not loaded fast enough? Especially in the built package (after running npm run build). E.g. if you have a file with content: export const config = { baseUrl: window.BASE_URL } I think if you import that config afterwards (import { config } from "...") then config.baseUrl could be undefined.config.js at the top of index.html. So the js files will load synchronously, it will load your bundle js only after config.js.src dynamicallyYou can store you JSON file in the public/ folder and it'll automatically provide this file when you host your Create React App.
Something like: /public/my-configuration-file.json
then when you restart your application:
localhost:3000/my-configuration-file.json
will provide you this json file.
You could create a custom hook that reads a "public" config file using fetch.
// This path is relative to root, e.g. http://localhost/config.json
const configFile = './config.json'
export function useConfig() {
const [config, setConfig] = useState(initialConfig);
useEffect(() => {
(async function fetchConfig() {
try {
const response = await (await fetch(configFile)).json();
setConfig(response);
} catch (e) {
console.log(e);
}
}());
}, []);
return config;
}
Then use it anywhere in you app
function App() {
const config = useConfig();
return (
<div>{config.foo}</div>
);
}
You'll always have an up to date non-cached version of it's data.
As an alternative you can add your config parameters to the .env file with REACT_APP_ prefix, and then read them in your code via process.env:
.env file:
# Create React App config:
PORT=8000
BROWSER=none
# Custom application config:
REACT_APP_CONFIG_PARAM=some_value
App.tsx file:
export const App = () => {
return <div>config value is: {process.env.REACT_APP_CONFIG_PARAM}</div>
}
And in your browser you'll see config value is: some_value