reactjs - 将 Docker 变量传递给 React index.html 文件
问题描述
我已经熟悉将 Docker 环境变量传递给 React 应用程序,方法是在docker-compose.yml
文件中的变量前面加上“REACT_APP_”字符串。
但是,我想在index.html
加载实际 React 应用程序的入口点中做类似的事情。
上下文:假设您想为 Google API 传递一个 Google API 密钥,并且您想通过 docker-compose 而不是编辑 index.html 在开发和生产 Docker 容器之间进行交换。
甚至可能吗?
解决方案
上个月我写了一篇关于类似的相关主题的博客文章——如果这有帮助,请告诉我:https ://www.brandonbarnett.io/blog/2018/05/accessing-environment-variables-from-a-webpack-捆绑在一个码头集装箱/
TL;DR:创建一个 shell 脚本,在您的 Web 服务器容器中自动生成一个静态 JS 配置文件。就是这样:
配置.js
#!/bin/bash
echo "window.appConfig = { API_URL: '${API_URL}'} " >> config.js
cat config.js
apachectl -D FOREGROUND
Dockerfile
COPY --from=build-env /src/config.sh .
RUN ["chmod", "+x", "./config.sh"]
CMD ["/usr/local/apache2/htdocs/config.sh"]
docker-compose.yaml
...
environment:
- API_URL=http://localhost:8082
...
索引.html
<!-- config.js has to come before your bundle -->
<script src="config.js"></script>
<script src="dist/bundle.js"></script>
推荐阅读
- java - 为什么查询谷歌云文件返回一个空列表?
- git - 在 git 中 rebase 时如何记录合并冲突解决方案?
- python - 对于 scipy 中的非中心卡方,输入“nc”是如何定义的?
- java - 用@DataJpaTest 注释的测试不是用@Autowired 注释的自动装配字段
- wpf - 为网格背景使用 DrawingBrush 资源
- ruby-on-rails - 在引发错误的方法中调用 RSpec 测试 Rollbar
- ios - 表格视图中的行不会扩展它的宽度并且是堆叠的 Swift
- eclipse-cdt - Eclipse CDT 将 #ifndef 下的错误部分代码变灰
- r - 读取 csv 文件,其中一个变量的值针对 R 中的每个观察值扩展为多行
- c# - 如何使用 C# HttpClient 发送未编码的表单数据