Angular:使用 ng serve 将 environment.ts 替换为特定于配置的文件

Angular: Replacing environment.ts with configuration specific files with ng serve

我有一个 Angular 应用程序,它使用 environment.ts 文件来设置诸如服务器 url 之类的东西。

我知道我可以使用 angular.json 中指定的 构建配置 在构建时替换文件,例如将 environment.ts 替换为 environment.prod.ts.

我想要与 ng serve 类似的内容,例如发射

ng serve --configuration=production

并用 environment.prod.ts 替换 environment.ts

我这可能吗? ng serve?

中使用哪些设置的命令行参数有更好的驱动方式吗

你说的ng serve --configuration=production其实是把environment.ts换成了environment.prod.ts。它已在 Angular.

中定义

如果您想根据配置进行其他替换(即替换更多文件),请转到 angular.json 并遵循以下结构:

  1. build下新建一个配置名:configurations
  2. fileReplacements 数组中填写您要替换的文件
  3. serve:configurations 下创建一个新标签,并引用您刚刚创建的标签。
  4. 启动服务,例如:ng serve --c=configuration-name(注意 --c--configuration 相同)

示例:

{
  . . .
  "projects": {
    "your-project-name": {
      . . .
      "architect": {
        "build": {
          . . .
          "options": { . . . },
          "configurations": {
            "production": { . . .  },
            "configuration-you-want-to-create": {
              "fileReplacements": [
                {
                  "replace": "src/path-to-file.original",
                  "with": "src/path-to-file.tobereplaced"
                },
                {
                  "replace": "src/other-path-to-file.original",
                  "with": "src/other-path-to-file.tobereplaced"
                }
              ]
            }
          }
        },
        "serve": {
          . . .
          "options": {. . .},
          "configurations": {
            "production": { . . .},
            "configuration-you-want-to-create": {
              "browserTarget": "your-project-name:build:configuration-you-want-to-create"
            }
          }
        },
        . . .
      }
    }},
  . . .
}