是否有任何方法可以在运行时或部署时(而不是在构建时)为web-app API调用配置API_URL



我正在使用Webpack捆绑我的React应用程序。

在生产中,我使用Dockerfile来提供使用npm build和Nginx生成的静态文件。然后使用Ansible部署这个docker映像。

现在,我必须在构建时使用环境文件或使用Webpack构建时设置为服务器请求指定API_URL

但是,我希望能够在部署时指定此URL,因为那时我只知道服务器URL。

我尝试过的:

  • 我可以装载Docker卷来更改变量,但我想避免更改缩小的代码。

  • 我尝试在assets中使用config.json文件,但在JS代码中导入该文件时,Webpack将其解析并内联加载为缩小的JS代码,并且我不能仅替换assets中的config.json文件。

  • 在运行时从公共URL获取config.json文件使我等待,然后才能进行任何API调用,并且在解析该文件之前,所有API请求都将发送到undefinedURL。

  • 我尝试的另一种方法是在Webpack中分割块并分割config.json文件。我可以编辑的缩小文件如下:

    !function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r(r.s=164)}({164:function(e){e.exports=JSON.parse('{"apiBaseURL":"http://localhost:3000"}')}});
    

有没有一种更简单的方法来解决这个问题,我可能缺少这种方法?

这是我的Dockerfile供参考:

## Build the app
FROM node:12-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci --silent
COPY . /app
RUN npm run build
## Expose port and start the app using nginx
FROM nginx:1.16.0-alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY --from=build /app/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

对我来说,我通过添加环境变量来解决它。

诀窍是在head标记中注入一个js脚本。

<script src="/config.js"></script>

您可以为该文件config.js提供内容:

window._env_ = {
API_URL: "http://localhost:3000",
};

通过这种方式,您可以将变量_env_公开给JS窗口对象,并在代码中的任何位置使用它。

以下资源非常有用:https://www.freecodecamp.org/news/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70/

最新更新