首页 > 解决方案 > 将 Docker 变量传递给 React index.html 文件

问题描述

我已经熟悉将 Docker 环境变量传递给 React 应用程序,方法是在docker-compose.yml文件中的变量前面加上“REACT_APP_”字符串。

但是,我想在index.html加载实际 React 应用程序的入口点中做类似的事情。

上下文:假设您想为 Google API 传递一个 Google API 密钥,并且您想通过 docker-compose 而不是编辑 index.html 在开发和生产 Docker 容器之间进行交换。

甚至可能吗?

标签: reactjsdocker

解决方案


上个月我写了一篇关于类似的相关主题的博客文章——如果这有帮助,请告诉我: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>

推荐阅读