Angular 构建角度应用程序时的不同环境配置

Angular 构建角度应用程序时的不同环境配置,angular,environment-variables,Angular,Environment Variables,我正在使用Angular 9,我有一个config.json文件,它是在运行时加载的。我有dev/config.json和prod/config.json,它们的加载取决于我是在本地运行应用程序还是为生产构建应用程序。到目前为止,我一直在手动注释文件路径,如下所示: // this.configPath = '/config/config-dev.json'; this.configPath = '/config/config-prod.json'; 如果路径始终相同,则更方便

我正在使用Angular 9,我有一个
config.json
文件,它是在运行时加载的。我有
dev/config.json
prod/config.json
,它们的加载取决于我是在本地运行应用程序还是为生产构建应用程序。到目前为止,我一直在手动注释文件路径,如下所示:

  // this.configPath = '/config/config-dev.json';
     this.configPath = '/config/config-prod.json'; 
如果路径始终相同,则更方便:

     this.configPath = '/config/config.json'; 
相应的config.json将被复制,这取决于我是在本地运行还是在为prod构建:例如,在angular.json中

"architect": {
        "build": {        
          "options": {                
            "assets": [
              "src/favicon.ico",
              "src/favicon-16x16.png",
              "src/favicon-32x32.png",
              "src/assets",
              "src/config/dev/config.json",
           or "src/config/prod/config.json",

是否可以设置
angular.json
来检测应该使用哪个配置文件并将其复制到配置文件夹中?

因为angular版本高于4。他们提供了一个内置函数,您可以在其中处理
文件替换
。这是给你的礼物

例如,假设您有这样一个文件结构

└──myProject/src/config/
               └──config.ts
               └──config.prod.ts
               └──config.stage.ts
"configurations": {
   "production": {
     "fileReplacements": [
       {
         "replace": "src/environments/config.ts",
         "with": "src/environments/config.prod.ts"
       }
     ],
     ...
您只需设置angular应替换为
config.ts
的文件,具体取决于您将使用的构建环境

像这样的

└──myProject/src/config/
               └──config.ts
               └──config.prod.ts
               └──config.stage.ts
"configurations": {
   "production": {
     "fileReplacements": [
       {
         "replace": "src/environments/config.ts",
         "with": "src/environments/config.prod.ts"
       }
     ],
     ...
要使用生产配置生成,请运行以下命令:

 ng build --configuration=production
注意:要放入
config.ts
的属性应该 开发环境是默认的。所以每次你 转到
service
your application,这些是将要提取的值