如何在后端应用程序等前端 js 应用程序中使用变量替换? [英] How to use variable substitution in Frontend js applications like backend applications?

查看:18
本文介绍了如何在后端应用程序等前端 js 应用程序中使用变量替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为一些应该非常简单的事情找到一个优雅的解决方案.我正在使用 create-react-app 开发 React 应用程序,并且在将代码部署到不同环境(例如在 Azure 中)时,我试图找到一种简单的方法来替换变量(例如 API 地址).

I'm trying to find an elegant solution to something which should be really simple. I am working on a React app using create-react-app and I'm trying to find an easy way to substitute variables (eg. API Address) when deploying code to different environments for example in Azure.

到目前为止,我一直在使用 .env 和 .env.production 文件来存储变量,只要我们只有一个环境,它们就可以很好地工作.但由于我计划总共拥有三个环境(测试、质量检查和生产),因此我必须找到更好的解决方案.

So far I've been using a .env and .env.production files to store the variables, which work great as long as we only have one environment. But as I'm planning to have three environments in total (test, qa and production) I have to find a better solution.

一种方法是在我们的 CI 构建的 npm 构建阶段替换变量.这种方法可行,但变量被注入到 bundle 中,因此此构建不适用于其他环境,我们对为每个环境创建一个构建不感兴趣.

One approach would be to substitute variables in the npm build stage of our CI build. This approach would work, but variables are injected to the bundle , so this build does not works for another environments and we are not interested in creating one build per environment.

我曾尝试在 Azure 中使用应用程序设置,并创建我自己的环境变量,但在我的 React 代码中使用 process.env 根本无法使用这些变量.

I've tried to use Application Settings in Azure, and creating my own Environment Variables, but these variables simply aren't available using process.env in my React code.

有没有办法在发布网页时轻松注入这些变量?或者,我们可以在 Azure 或其他提供商中以某种方式配置这些吗?或者有其他解决方案吗?

Is there a way to easily inject these variables when releasing the web? Alternatively can we configure these in Azure or another provider somehow? Or is there another solution?

推荐答案

使用 react、vue、angular 或其他基于 javascript 的框架开发的复杂应用程序与后端应用程序(java、nodejs、python 等)具有相同的问题或要求:如何读取配置?

Complex applications developed with react, vue, angular or other javascript based frameworks has the same problem or requirement as backend applications (java, nodejs, python, etc): How read configurations?

在这里,我将列出一些处理 javascritpt 框架配置的方法,从简单到托管解决方案.其中一些用于后端应用程序.

Here I will list some some approaches to work with configurations for javascritpt frameworks, from simple to manged solutions. Some of them are used for backend applications.

当我们谈论 javascript 框架时,只需在您的应用程序启动时创建全局变量,这将可用于您的所有脚本:

As we are talking about javascript frameworks, just create global var at the startup of your application and this will be available for all your scripts:

<html>
  <header>
    <meta charset="utf-8">
    <title>This is title</title>
    <script>
        var myVar = "global value"; // Declare a global variable
    </script>
    <script>
        console.log("from another script:"+myVar);
    </script>
  </header>
  <body>
    Hello world
  </body>
</html>

当然,源代码中的硬编码 url 不是一种选择,但请理解这是下一个方法的切入点.几乎所有的都基于这种方法或做类似的事情.

Of course, a harcoded url in the source code is not an option but understand this is the entry point to the next approaches. Almost all of them are based on this approach or do something similar.

Webpack 为我们提供了多种机制,例如 DefinePlugin

Webpack provide us with several mechanisms like DefinePlugin

new webpack.DefinePlugin({
  API_BASE_URL: JSON.stringify(process.env.API_BASE_URL)
})

DefinePlugin 是一种直接文本替换.Webpack 将查找标识符并将其替换为给定的字符串.以下示例说明了其工作原理.

The DefinePlugin is a direct text replacement. Webpack will look for the identifier and replace it with the given string. The following example illustrates how that works.

你可以像使用全局变量一样使用这个变量:

You could use this variable as if it were a global variable :

$.ajax({
    type: "GET",
    url: API_BASE_URL+'/odds?date=2019-01-19',
    dataType: 'json',
    success: function (data) {
      ...
    }
  });
}

这里有更多 webpack 机制:https://stackoverflow.com/a/40416826/3957754

Here more webpack mechanisms : https://stackoverflow.com/a/40416826/3957754

优点:

  • 设置或定义多个变量并在整个应用程序中使用它们的简单方法.
  • 使用像 jenkins 这样的 C.I 服务器,您可以设置所有配置并构建您的工件,然后部署它:

export API_BASE_URL=http://awesome.api.com
export ENDPOINT_DETAIL=/detail
export ENDPOINT_FAVOURITE=/favourite
export MODULES=user,guest,admin,configure

npm run build

缺点

  • 在构建阶段注入变量.配置中的更改将需要重新构建和重新部署您的应用程序.

检查这个答案:

主要思想是将您的所有配置、设置或属性放在一个站点中,并且您的所有应用程序都必须以安全的方式检索这些值.如今,从最终应用程序中检索此配置的最常用技术是对平台发布的 api rest 执行 http 请求.

The main idea is put all your configurations, settings or properties in one site and all your applications must retrieve this values in a secure way. Nowadays the most common technique to retrieve this configuration from final application is perform an http request to an api rest published by the platform.

这种平台是微服务架构的完美搭档.此外,我还可以将其用于微前端.

This kind of platforms are the perfect partners for a microservice architecture. Also I was able to use it for microfrontends.

这里有一些平台:

  • 配置器
    • 这是一个 nodejs 应用程序,可让您集中和管理所有应用程序的配置.
    • Consul 是一种服务网格解决方案,提供具有服务发现、配置和分段功能的全功能控制平面.

    您可以将这些平台之一与 webpack 方法结合使用.因此,您可以在 webpack 的构建阶段或使用 jenkins 等 C.I 服务器使用 api rest,而不是手动导出环境变量.

    You can use one of these platforms in conjunction with webpack approach. So instead to manually environment variables export you can consume the api rest at build stage in webpack or with your C.I server like jenkins.

    优势

    • 以上评论的所有内容.

    缺点

    • 与在不同于应用程序的另一台服务器上进行配置相比,独特的属性文件或手动环境导出可以轻松快速地进行配置.

    假设您的网站在 http://myapp.com 上提供服务,您可以发布另一个端点,例如 http://myapp.com/settings.此端点将使用 AJAXCLIENT SIDE 返回您的微前端或 Web 应用程序所需的所有设置.

    Asumming that your web is served at http://myapp.com, you could publish another endpoint like http://myapp.com/settings. This endpoint will return all the settings required by your microfrontend or web application at CLIENT SIDE using AJAX.

    在你的javascript应用程序中,在入口点(在react、vue等中通常是App.js),我的意思是在渲染机制之前,你可以使用http://myapp.com/settings 并作为全局变量公开给您的应用程序.您还可以将其保存在可用的存储空间之一中,例如 localStorage、sessionStorage 等

    In your javascript application, in the entry point (commonly App.js in react, vue, etc), I mean before render mechanisms, you can consume http://myapp.com/settings and expose as global vars to your application. You can also save it in one of the storages available like, localStorage, sessionStorage, etc

    优势

    • 您的配置更改即可使用,无需重新构建应用程序.只需执行页面刷新即可再次执行 javascript 中的入口点.
    • 您可以在 /settings
    • 的后端控制器中使用方法 #3
    • Changes in your configurations are ready to use without rebuild the application. Just perform a page refresh to execute again the entry point in your javascript.
    • You can use the approach #3 in the backend controller of your /settings

    缺点

    • 相对于 ajax http 请求,预硬编码变量会立即加载.

    这篇关于如何在后端应用程序等前端 js 应用程序中使用变量替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆