11

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

Community
  • 1
  • 1
Steven
  • 18,786
  • 46
  • 149
  • 250

2 Answers2

31

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.

Bryan Fillmer
  • 503
  • 3
  • 4
  • 1
    ok for static settings, but when loading config is expensive and you don't want it to execute that logic every time that file is referenced. Looking for a way to load this on startup and re-use – Sonic Soul Apr 26 '19 at 19:59
  • 1
    @SonicSoul The imports are cached, so the config object itself is not computed multiple times as long as you use import statement. – Thava Apr 27 '19 at 06:00
  • @Thava oh interesting! i will test this! – Sonic Soul Apr 28 '19 at 15:05
1

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.

sntnupl
  • 1,221
  • 1
  • 10
  • 8
  • i had to use this before , but as your api endpoints grows , your webpack file is becomes a mess, the best solution i found so far is a `ServiceConfig.js` file that uses a singleton pattern to implement all fetch actions of your webApp... – amdev Oct 28 '18 at 22:38