首页 > 解决方案 > 如何在角度的外部extconfig.js文件中动态获取基于构建环境的环境变量

问题描述

我在 angular.json 文件中有配置指向不同构建的不同“url”

角.json

configuration:{
   'dev':{
      "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
    },
   qa:{

  }
}

环境.dev.ts

export const environment = {
 appServer: "https://....."
}

环境.prod.ts

export const environment = {
 appServer: "https://....."
}

我想创建一个保存在资产中的 extconfig.js 文件(外部 js)并将其放入 angular.json 文件中

配置.js

var baseUrl = '' ; <==========// environment.appServer based on build condition

它应该用于在通过 "ng serve --configuration=devng build --configuration=prod.

这是必需的,因为“extconfig.js”文件将包含全局变量,其中包含为可能需要调用的其他外部 js 服务的baseUrl配置ajax变量

标签: angular

解决方案


如果我理解正确,您可以在同一文件夹下创建 aconfig.prod.ts和 a config.ts,每个文件夹都包含一个版本的 appServer url。然后您可以从服务中的文件夹中导入您的配置。

import { extConfig } from './config-specifics';

var baseUrl = extConfig.appServerUrl

在你的angular.json.

"fileReplacements": [
        {
          "replace": "apps/app-name/src/app/config-specifics/config.ts",
          "with": "apps/app-name/src/app/config-specifics/config.prod.ts"
        }
      ]

推荐阅读