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

查看:100
本文介绍了如何在前端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.

I曾尝试在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编码的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这样的CI服务器,您可以设置所有配置并进行构建您的工件然后进行部署:

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

缺点


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

检查此答案:

  • What is the best way to change application configurations in a CI environment

主要思想是将所有配置,设置或属性放在一个站点中,所有应用程序都必须检索此内容值以安全的方式。如今,从最终应用程序检索此配置的最常用技术是对平台发布的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应用程序,可用于集中化和所有应用程序的管理配置。

    • http://www.therore.net/java/2015/05/03/distributed-configuration-with-zookeeper-curator-and-spring-cloud-config.html

    • Consul是一种服务网格解决方案,提供具有服务发现,配置和分段功能的全功能控制平面。 / li>
    • Consul is a service mesh solution providing a full featured control plane with service discovery, configuration, and segmentation functionality.

    您可以将这些平台之一与webpack方法结合使用。因此,代替手动导出环境变量,您可以在构建阶段在webpack或像jenkins这样的CI服务器上使用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 。该终结点将使用 AJAX 返回客户端上的Microfrontend或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应用程序中,在进入点(通常是App.js在react,vue等中),我的意思是在渲染机制之前,您可以使用 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中的入口点

    • 您可以在 /的后端控制器中使用方法#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天全站免登陆