【问题标题】:Pass Docker variable to React index.html file将 Docker 变量传递给 React index.html 文件
【发布时间】:2018-06-26 13:39:32
【问题描述】:

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

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

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

有可能吗?

【问题讨论】:

    标签: reactjs docker


    【解决方案1】:

    我上个月写了一篇关于类似的相关主题的博文——如果有帮助,请告诉我:https://www.brandonbarnett.io/blog/2018/05/accessing-environment-variables-from-a-webpack-bundle-in-a-docker-container/

    TL;DR:创建一个在您的 Web 服务器容器中自动生成静态 JS 配置文件的 shell 脚本。方法如下:

    config.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
    ...
    

    index.html

    <!-- config.js has to come before your bundle -->
    <script src="config.js"></script>  
    <script src="dist/bundle.js"></script>
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 好电话。提取了一些内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多