我的React应用程序使用webpack捆绑资源,然后将这些资源放入Docker映像进行部署 . 我有一组配置变量,我想添加到JSON文件中,我的应用程序可以在运行时读取该文件 . 例如,API密钥或API URL,可随时更改 . 此JSON文件将在需要时通过Kubernetes Configmaps和Secrets进行更新 .
我查看了许多帖子和解决方案,但它们似乎都没有正常工作 .
例如,如果我尝试以下链接中的解决方案,JSON文件将与其他资源捆绑在一起 . 我必须重新启动webpack / build以获取JSON文件中的更改以反映在我的应用程序中 .
Webpack -- include configuration file as external resource
How to store Configuration file and read it using React
Any way to use webpack to load a resource at runtime?
处理我的要求的最佳方法是什么?
我的项目结构如下:
├── config
│ └── jsonConfig.prod.json (This will be updated on the server)
├── src (My react application code which gets bundled via webpack)
jsonConfig.prod.json的内容:
{
"name": "my-app"
}
我的webpack.config.js
externals: {
'jsonConfig': JSON.stringify(PRODUCTION ? require('./jsonConfig.prod.json') : require('./jsonConfig.dev.json'))
}
在我的代码中(在 npm run build
之后):
import * as jsonConfig from 'jsonConfig';
console.log(jsonConfig.name); // my-app
我改变了jsonConfig.prod.json的内容:
{
"name": "my-app2"
}
在我的代码中(与之前相同的构建):
import * as jsonConfig from 'jsonConfig';
console.log(jsonConfig.name); // Still my-app