﻿# 如何在 Angular 16 加入 environments.ts 環境變數支援

從 Angular 15 開始，預設透過 `ng new` 建立的專案都不會有之前的 `environment.ts` 環境變數檔與相關設定，由於看到有人問到這個問題，而且我發現官方文件都沒有相關說明，因此我特別撰文說明如何把這個設定加回去。

### 設定過程

1.  建立 Angular 16 全新專案
    
    ```bash
    ng new demo1 --routing --style css
    ```
    
2.  使用 Visual Studio Code 開啟專案
    
    ```bash
    code demo1
    ```
    
3.  建立兩個環境變數檔
    
    第一個 `src/environments/environment.ts` 檔案，內容如下：
    
    ```javascript
    export const environment = {
      production: false
    };
    ```
    
    第二個 `src/environments/environment.prod.ts` 檔案，內容如下：
    
    ```javascript
    export const environment = {
      production: true
    };
    ```
    
4.  調整 `angular.json` 設定檔
    
    找到 `.projects.demo1.architect.build.configuration.production` 區段，加入以下設定值：
    
    ```json
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ],
    ```
    

### 測試成果

1.  修改 `src\app\app.component.ts` 程式
    
    ```typescript
    import { Component } from '@angular/core';
    import { environment } from 'src/environments/environment';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = environment.production ? 'Production' : 'Development';
    }
    ```
    
2.  啟動開發伺服器在 `production` 模式
    
    ```bash
    ng serve --configuration=production
    ```
    
    當啟動在 `production` 模式時，我們在 `angular.json` 設定檔中的 `fileReplacements` 設定就會生效，並且在建置過程中自動將 `src/environments/environment.ts` 替換成 `src/environments/environment.prod.ts` 檔案！
    
3.  開啟 http://localhost:4200 就會看到以下 `Production app is running!` 字樣
    
    ![image](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/ead3ba1f382cf924954d-f29580fb-829c-40ef-b18d-7f1ff1770fa4.webp)
    

### Angular CLI 懶人包

其實從 Angular CLI 15.1 開始，就有一個內建的 `ng generate environments` 命令可以幫你快速產生 `environment.ts` 與調整 `angular.json` 相關設定，可謂是懶人的救星！👍

```bash
ng generate environments
```

> 相關的官網文件在此：[Configure environment-specific defaults](https://angular.io/guide/build#configure-environment-specific-defaults)

### 相關連結

-   [Angular 15: what happened to environment.ts - DEV Community](https://dev.to/this-is-angular/angular-15-what-happened-to-environmentts-koh)
-   [Angular - Building and serving Angular apps](https://angular.io/guide/build)
