使用Typescript处理Angular中环境的最佳方法

时间:2019-04-12 08:18:13

标签: angular typescript angular-cli

我目前正在研究一种策略,以便在Angular CLI中尽可能轻松地处理多个环境。

为此,我遵循以下方法: enter image description here

我的目标是让不同REST终结点的基本URL仅有一次,并且所有环境都应该具有它们(扩展之类的东西)。

实现此目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用多个环境文件,这是您可以使用的方法,并且在构建时必须指定配置(例如:prod,test,uat)

  • 您必须将所有配置添加到angular.json文件

    "configurations": {
        "production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "2mb",
              "maximumError": "5mb"
            }
          ]
        },
        "develop": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.develop.ts"
            }
          ]
        },
        "release": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.release.ts"
            }
          ]
        },
        "uat": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.uat.ts"
            }
          ]
        },
      }
    

为每个文件添加您的网址,并且在本地构建或提供应用程序时,必须指定配置

ng build --configuration=uat // for uat env

ng serve --configuration=uat 

ng build --prod // for production env

以这种方式导入它,它将根据选择的配置选择正确的

import { environment } from 'src/environments/environment';

答案 1 :(得分:0)

如果使用的是webpack,则可以创建一个environment.ts文件,其中所有环境特定的数据都作为对象中的属性。...

    {
        environment: 'dev',
        baseurl: 'http://myBaseUrl'
    }

为每个环境(prod,qa等)创建具有相同对象和属性的单独文件。当您需要环境信息时,导入普通的environment.ts文件。...

然后在每个webpack配置中使用NormalModuleReplacementPlugin ...

    new webpack.NormalModuleReplacementPlugin(/\.\/environment\./, './environment.qa.ts')

您基本上是在告诉webpack,无论我将环境导入到哪里,都将其替换为带有environment.qa(或任何版本)的环境

相关问题