how can we use environment variable in angular version >=2

后端 未结 3 801
离开以前
离开以前 2021-01-02 06:44

I am now reading the angular4 doc, and noticed, there is one folder, environments, and under which, there are multiple environment files, such as environment.ts, environment

3条回答
  •  离开以前
    2021-01-02 07:31

    Check out envsub for an easy way to build your configuration file src/environments/environment.ts by substituting environment variables into a handlebars template file src/environments/environment.hbs using a package called envsub.

    Make sure to delete the environments key from .angular-cli.json.

    As an example, the content of src/environments/environment.hbs could be something like:

    export const environment = {
        production: ${ MYAPP_PRODUCTION }
    };
    

    To substitute MYAPP_PRODUCTION with false run the following from the terminal.

    MYAPP_PRODUCTION=false envsub src/environments/environment.hbs src/environments/environment.ts
    

    The resulting file src/environments/environment.ts will be

    export const environment = {
        production: false
    };
    

    You can add an additional script to package.json to build your configuration file.

    "scripts": {
        "config": "envsub src/environments/environment.hbs src/environments/environment.ts",
    }
    

    Build your configuration by running something like the following in your terminal:

    MYVAR=test npm run config
    

    Remember to exclude src/environments/environment.ts from version control. For git you can use a .gitignore file.

提交回复
热议问题