Picci
Picci

Reputation: 17762

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

I have an Angular app which uses environment.ts file to set stuff like urls of servers.

I know that I can use build configurations specified in angular.json to replace files at build time, e.g. replace environment.ts with environment.prod.ts.

I would like something similar with ng serve, e.g. launching

ng serve --configuration=production

and having environment.prod.ts replacing environment.ts.

I this possible? Are there better ways to drive with command lines parameters which settings are used in ng serve?

Upvotes: 8

Views: 11774

Answers (1)

Sergio
Sergio

Reputation: 819

The one you say, ng serve --configuration=production actually replaces environment.ts with environment.prod.ts. It is already defined in Angular.

In case you want to have another replacements (i.e., more files replaced) depending on configuration, go to you angular.json and follow the structure:

  1. Create a new configuration name under build:configurations
  2. Fill in the fileReplacements array with your files to be replaced
  3. Under serve:configurations create a new tag, and reference to the one you just created.
  4. Launch serve, like: ng serve --c=configuration-name (note that --c is the same as --configuration)

Example:

{
  . . .
  "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"
            }
          }
        },
        . . .
      }
    }},
  . . .
}

Upvotes: 19

Related Questions