如何在 React 中使用配置文件? [英] How can I use a config file in React?
问题描述
假设我有 5 个 jsx 文件,每个文件都使用一些配置参数.我的 index.js 文件导入了所有这 5 个 jsx 文件.
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.
我的 jsx 文件有没有办法从全局 JS 对象中获取数据,而不是让我的配置数据分布在 5 个文件中?
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?
我看过一些示例,但我无法让它们发挥作用.
JS6 导入功能 |使用 webpack 的示例
I've seen some examples, but I've not been able to get them to work.
JS6 import function | Example using webpack
推荐答案
假设 ES6:
config.js
export const myConfig = { importantData: '', apiUrl: '', ... };
那么:
jsxFileOne.js, jsxFileTwo.js, ...
import { myConfig } from 'config.js';
还有其他方式导入 &利用 webpack 全局导出内容,但这应该会让你开始.
There are other ways to import & export things globally leveraging webpack, but this should get you started.
这篇关于如何在 React 中使用配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!