Angular15默认取消environment.prod.ts后如何区分开发与生产环境
Angular 15 区分开发与生产环境的方法
方法一:利用 Angular CLI 内置的环境变量
Angular CLI 在构建时会自动设置NODE_ENV变量,直接在代码中读取即可判断环境:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class EnvService { get isProduction(): boolean { return import.meta.env.NODE_ENV === 'production'; } }
在组件或服务中注入这个服务,就能快速区分当前是开发还是生产环境。
方法二:手动恢复传统环境文件模式
如果习惯用独立的环境配置文件,可以手动创建并关联到构建流程:
- 在
src/environments目录下创建两个文件:environment.ts(开发环境):export const environment = { production: false, apiBaseUrl: 'http://dev.example.com/api' };environment.prod.ts(生产环境):export const environment = { production: true, apiBaseUrl: 'http://prod.example.com/api' };
- 修改
angular.json中的构建配置:
找到projects -> 你的项目名 -> architect -> build -> configurations -> production,添加文件替换规则:"fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] - 构建时执行
ng build --configuration production,CLI会自动替换环境文件。
方法三:通过外部配置文件动态加载
如果需要在部署阶段灵活修改配置,可借助APP_INITIALIZER在应用启动前加载外部配置:
- 在
src/assets下创建config.json:
生产部署时直接替换这个文件即可。{ "production": false, "apiBaseUrl": "http://dev.example.com/api" } - 编写配置加载服务:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ConfigService { config: any; constructor(private http: HttpClient) {} loadConfig() { return this.http.get('/assets/config.json') .toPromise() .then(data => this.config = data); } } - 在
app.module.ts中配置初始化器:import { APP_INITIALIZER, NgModule } from '@angular/core'; import { ConfigService } from './config.service'; export function initApp(configService: ConfigService) { return () => configService.loadConfig(); } @NgModule({ providers: [ { provide: APP_INITIALIZER, useFactory: initApp, deps: [ConfigService], multi: true } ] }) export class AppModule {}
方法四:构建命令传递自定义参数
通过--define参数在构建时直接传递环境标识:
- 开发构建:
ng serve --define=production=false - 生产构建:
ng build --define=production=true
然后在代码中声明并使用这个变量:
declare const production: boolean; export const isProduction = production;
内容的提问来源于stack exchange,提问作者user15163984
相关产品推荐
相关产品推荐

