Angular:使用 ngserve 用配置特定文件替换environment.ts

Pic*_*cci 7 angular-cli angular

我有一个 Angular 应用程序,它使用environment.ts文件来设置服务器 url 等内容。

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

我想要类似的东西ng serve,例如启动

ng serve --configuration=production
Run Code Online (Sandbox Code Playgroud)

并有environment.prod.ts替换environment.ts.

我这可能吗?是否有更好的方法来使用使用设置的命令行参数进行驱动ng serve

小智 18

你说的那个,ng serve --configuration=production实际上替换environment.tsenvironment.prod.ts. 它已经在 Angular 中定义了。

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

  1. 在以下位置创建一个新的配置名称buildconfigurations
  2. fileReplacements用要替换的文件填充数组
  3. 在 下serveconfigurations创建一个新标签,并引用您刚刚创建的标签。
  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"
            }
          }
        },
        . . .
      }
    }},
  . . .
}
Run Code Online (Sandbox Code Playgroud)