How can I use a config file in React?

本小妞迷上赌 提交于 2021-02-18 21:00:48

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37066758/how-can-i-use-a-config-file-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!