深度优先

这个家伙好懒,除了文章什么都没留下

0%

【Angular】配置文件之环境配置

假设有三个环境:开发环境(dev)、测试环境(test)、生产环境(prod)。
当我们构建参数时会用到 –prod来指定应用执行环境。脚手架会根据指定的值加载对应的环境配置文件。如:ng build –prod=dev –aot 就是build开发环境的包。那么我们就从这里开始看看Angular项目里环境该怎么配置。

  1. 首先要找到.angular.json文件的production关键词进行如下配置:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    "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
    },
    "dev": {
    "fileReplacements": [{
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.dev.ts"
    }],
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "extractCss": true,
    "namedChunks": false,
    "aot": true,
    "extractLicenses": true,
    "vendorChunk": false,
    "buildOptimizer": true
    },
    "test": {
    "fileReplacements": [{
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.test.ts"
    }],
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "extractCss": true,
    "namedChunks": false,
    "aot": true,
    "extractLicenses": true,
    "vendorChunk": false,
    "buildOptimizer": true
    }
    }
  2. 再进入environments文件夹
    文件目录:
    ├─ environments
    │ ├─ environment.ts
    │ ├─ environment.test.ts
    │ ├─ environment.prod.ts 开发环境 :

  • environment.ts
    1
    2
    3
    4
    5
    export const environment = {
    production: true,
    envName: 'prod',
    apiBaseURL: 'http://10.**.**.***:81',
    };
    测试环境:
  • environment.test.ts
    1
    2
    3
    4
    5
    6
    7
    // 测试环境
    // ng build --prod=test --aot
    export const environment = {
    production: false,
    envName: 'test',
    apiBaseURL: 'http://10.25.141.150:1111',
    };
    生产环境:
  • environment.prod.ts
    1
    2
    3
    4
    5
    6
    7
    8
    // 生产环境
    // ng build --prod=prod --aot
    export const environment = {
    production: false,
    envName: 'prod',
    apiBaseURL: 'http://10.25.141.150:81',
    };

  1. 在项目的相对路径引入环境再请求接口,代码如下:
    1
    2
    3
    4
    5
    6
    import { environment } from '../environments/environment';

    export const appConfig = {
    apiUrl: environment.apiBaseURL,
    };

    Angular6有些改动, 参考自:

作者:莫莫莫I
链接:https://www.jianshu.com/p/d9397954dc8f
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。