Javascript 如何在 React 中使用配置文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37066758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use a config file in React?
提问by Steven
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.
假设我有 5 个 jsx 文件,每个文件都使用一些配置参数。我的 index.js 文件导入了所有这 5 个 jsx 文件。
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?
不是让我的配置数据分布在 5 个文件中,有没有办法让我的 jsx 文件从全局 JS 对象中获取数据,该对象已从配置文件加载数据?
I've seen some examples, but I've not been able to get them to work.
JS6 import function| Example using webpack
我看过一些例子,但我无法让它们工作。
JS6 导入函数| 使用 webpack 的示例
回答by Bryan Fillmer
Assuming ES6:
假设 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.
还有其他方法可以利用 webpack 全局导入和导出内容,但这应该可以帮助您入门。
回答by sntnupl
If your project is built using Webpack, consider using node-env-file.
Example config file snippets:
如果您的项目是使用 Webpack 构建的,请考虑使用node-env-file。
示例配置文件片段:
development.envAPI_SERVER_URL=https://www.your-server.com
开发环境API_SERVER_URL=https://www.your-server.com
webpack.config.js
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.
在 js/jsx 代码中,您现在可以访问process.env.API_SERVER_URL
包含所需值的变量。
It seems dotenvpackage is more popular, you can try this out as well.
似乎dotenv包更受欢迎,你也可以试试这个。