一、背景
同一个项目,卖个不同的公司,需要进行OEM定制化开发。产品的logo、名称、及配置地址都不相同,因此在项目中处理这个问题。
二、解决方案
1、在项目启动时加载不同的配置文件,将固定不变的logo等信息动态注入到项目服务中去。
1)、在src/environments中新建自定义的配置文件
2)、在main.ts中注入配置的参数(DYNAMICENVIRONMENT 方便开发环境进行切换,新建个配置文件)
import { environment } from './environment.scan'; export const DYNAMICENVIRONMENT = environment;
import { enableProdMode, ViewEncapsulation } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; // TODO 开发环境需要更好此处的路径 import { environment } from './environments/environment'; import { DYNAMICENVIRONMENT } from '@env/dynamic.environment'; import { preloaderFinished } from '@delon/theme'; preloaderFinished(); if (environment.production) { enableProdMode(); } const bootstrap = () => { return platformBrowserDynamic([ { provide: 'ConfigModel', useValue: DYNAMICENVIRONMENT } ]).bootstrapModule(AppModule, { defaultEncapsulation: ViewEncapsulation.Emulated, preserveWhitespaces: false, }); }; bootstrap().then(() => { if ((<any>window).appBootstrap) { (<any>window).appBootstrap(); } });
3)、在需要这些信息的模块或者服务中注入这些参数
import { HttpClient} from '@angular/common/http'; import { environment } from '@env/environment'; @Injectable() export class ConfigureService { constructor( @Inject('ConfigModel') private config, private httpClient: HttpClient ) { // 处理开发环境和编译环境的灵活转换 if (environment.production) { this.config = environment; } }
2、配置build参数,根据参数打包时加载不同的配置文件。
1)、编译命令在package.json中的是
"build": "ng build --prod --build-optimizer",
修改为
"build": "ng build --prod --build-optimizer --configuration=shenhua",
默认的配置是configuration=production
2)、angular6脚手架的配置文件改成了angular.json,在angular.json中做如下修改(编译是默认的是production)
扫描二维码关注公众号,回复: 3271056 查看本文章configurations对象新增一个属性和build命令行中的配置“shenhua”要一致。修改“shenhua”的“fileReplacements”属性,路径是你新增的配置文件路径,打包时会加载你配置的文件。
"configurations": { "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] }, // 编译OEM相关配置 "shenhua": { "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "fileReplacements": [ { "replace": "src/environments/environment.shenhua.ts", "with": "src/environments/environment.shenhua.prod.ts" } ] } }
3)、angular6之前是在angular-cli.json中配置
"environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts", "custom": "environments/environment.custom.ts", }
bulid命令添加--env=custom
ng build --prod --aot --env=custom
3、需要动态修改的文件,例如项目的服务器地址(保存json文件,动态获取)
动态获取就在需要处理的服务通过HttpClient去获取就可以了