Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a config file in React?

Let's say I have 5 jsx files and each file uses some config parameter. My index.js file imports all of these 5 jsx files.

Instead of having my config data spread accross 5 files, is there a way for my jsx files to get the data from a global JS object which has loaded the data from a config file?

I've seen some examples, but I've not been able to get them to work.
JS6 import function | Example using webpack

like image 960
Steven Avatar asked May 06 '16 07:05

Steven


2 Answers

Assuming ES6:

config.js

export const myConfig = { importantData: '', apiUrl: '', ... };

Then:

jsxFileOne.js, jsxFileTwo.js, ...

import { myConfig } from 'config.js';

There are other ways to import & export things globally leveraging webpack, but this should get you started.

like image 121
Bryan Fillmer Avatar answered Oct 07 '22 05:10

Bryan Fillmer


If your project is built using Webpack, consider using node-env-file.
Example config file snippets:

development.env
API_SERVER_URL=https://www.your-server.com

webpack.config.js

const envFile = require('node-env-file');
...
const appSettingsFile = isDevBuild ? '/settings/development.env' : '/settings/production.env';

try {
    envFile(path.join(__dirname + appSettingsFile));
} catch (error) { 
    console.log("Failed to read env file!: " + __dirname + appSettingsFile);
}
...
plugins: [
    new webpack.DefinePlugin({
        "process.env": {
            API_SERVER_URL: JSON.stringify(process.env.API_SERVER_URL)
        }
    })
    ...
]

Inside your js/jsx code, you can now access process.env.API_SERVER_URL variable which will contain the required value.

It seems dotenv package is more popular, you can try this out as well.

like image 25
sntnupl Avatar answered Oct 07 '22 05:10

sntnupl