Steven
Steven

Reputation: 19425

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

Upvotes: 12

Views: 42487

Answers (3)

Shweta
Shweta

Reputation: 799

One purpose to add config.js file is to use static data which needs to be used all over the application.

Suppose we want our BASE URL to configure for local, test and prod environment then we can create a config file with different values based on the environment we are using so our main application code will be untouched, only the base url will be changed based on environment we are working upon.

  1. we can create "config.js" under project root directory.

    your_project_name > config.js

  2. You can add static data in config.js file

    export const configData = {

    BASE_URL: "https://your-domain.com/app-url/"

    }

  3. Now suppose you want to use the configData in "App.js" file under the src folder of project root directory

    import { configData } from "../Config";

    const verify_link = configData.BASE_URL + "any_custom_link";

  4. You can import and use the 'configData' wherever required all over your application the same way.

Hope it helps!

Upvotes: 0

sntnupl
sntnupl

Reputation: 1361

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.

Upvotes: 1

Bryan Fillmer
Bryan Fillmer

Reputation: 548

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.

Upvotes: 33

Related Questions