Angular生产开发环境变量的使用(env)
文章 819 0 0 0
发布时间:2022年02月09日

概述

根据环境变量配置不同的开发环境。

环境变量文件

路径

项目\src\environments\ 下有2个文件:environment.ts, environment.prod.ts

environment.prod.ts 生产环境
environment.ts 开发环境

默认的开发环境是用environment.ts 这个文件;

environment.ts

export const environment = {
    production: false,
    baseUrl: 'http://dev.zhuimengzhu.com'
};

environment.prod.ts

export const environment = {
    production: false,
    baseUrl: 'http://prod.zhuimengzhu.com'
};

如果你的文件位置路径跟我的不对应,请查看angular.json文件 如下:

"configurations": {
    "production": {
        // 此处便是你的环境配置文件路径
        "fileReplacements": [
            {
                "replace": "src/environments/environment.ts",
                "with": "src/environments/environment.prod.ts"
            }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "extractLicenses": true,
        "vendorChunk": false,
        "buildOptimizer": true,
        "budgets": [
            {
                "type": "initial",
                "maximumWarning": "2mb",
                "maximumError": "5mb"
            },
            {
                "type": "anyComponentStyle",
                "maximumWarning": "6kb",
                "maximumError": "10kb"
            }
        ]
    }
}

引入文件

import { environment } from '../environments/environment';

调用

constructor(Http: HttpClient) {
    this.http = Http;
    this.restServer = environment.baseUrl + '/api/index';
    this.imgurl = environment.imgUrl + '/';
}
评论专区
Q群
Q群
Q群
反馈
纠错
App