switch development mode and product mode by environments in Angular 5

1.2k views Asked by At

My angular-cli.json has environments array.

"environmentsSource": "environments/environment.ts"
"environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"

In environment.ts,

export const environment = {
      production: false
};

In environment.prod.ts

export const environment = {
      production: true
};

And in main.ts,

if (environment.production) {
    enableProdMode();
}

However I only have one package.josn file.

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build"

I have different environments such as dev/qa and prod. The urls are different, how can I switch the mode for just one package.json file?

The build and deploy process is automatedly. We can't change the setting when build.

2

There are 2 answers

0
Hello On BEST ANSWER

In main.ts, I checked the value of document.location.host. If it contains a specific substring then I

enableProdMode()
6
Marco On

You need to reference the configuration in the CLI.

Example to run the prod environment.

ng serve --configuration=prod

This will replace the environment.ts file by environment.prod.ts.

You can set all the needed variable (url, ...) in the environments files.

In the code, you only need to read the environment file. It will be replaced by the angular CLI configuration param. You can parameter this in angular.json file.

"configurations": {
    "prod": {
        "fileReplacements": [
            {
                "replace": "apps/afh/src/environments/environment.ts",
                "with": "apps/afh/src/environments/environment.prod.ts"
            }
        ],
        ...
    }
}