Angular实现一次打包,外部修改环境配置。
1 新建环境配置
2 修改angular.json打包配置,把配置环境独立打包出来。
"assets": [
"src/favicon.ico",
"src/assets",
"src/lib",
{
"glob": "**/*",
"input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
"output": "/assets/"
},
{
"glob": "**/*",
"input": "./node_modules/pspdfkit/dist/pspdfkit-lib/",
"output": "./assets/pspdfkit-lib/"
}
],
3 main.ts读取配置json,将配置项写入window.__env,(这里只有在生产环境读取外部配置)。
function getEnv() {
const configUrl = `./lib/config/config.prod.json`;
const xhr = new XMLHttpRequest();
xhr.open('GET', configUrl, false);
xhr.onload = () => {
if (xhr.status === 200 && xhr.readyState === 4) {
window['__env'] = Object.freeze(JSON.parse(xhr.response));
} else {
window['__env'] = Object.freeze({
status: 'error',
errorMsg: '读取配置文件失败'
});
}
};
xhr.send();
}
if (environment.production) {
enableProdMode();
window.console.log = () => { };
window.console.debug = () => { };
getEnv();
}
4 将window.__env中的配置项写入service。
env.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Environment {
production = false;
installation = '';
uiManageUrl = ''
apiTimeout = 10000;
universalServerUrl = '';
universalToken = '';
uiDBCache = false;
constructor() { }
}
env.service.provider.ts
import { environment } from 'src/environments/environment';
import { Environment } from './env.service';
export const EnvServiceFactory = () => {
let env;
if (environment.production) {
env = new Environment();
const browserWindow = window || {};
const browserWindowEnv = browserWindow['__env'] || {};
if (browserWindowEnv) {
for (const key in browserWindowEnv) {
if (browserWindowEnv.hasOwnProperty(key)) {
env[key] = window['__env'][key];
}
}
}
} else {
env = environment;
}
return env;
};
export const EnvServiceProvider = {
provide: Environment,
useFactory: EnvServiceFactory,
deps: [],
};
5 在app.module.ts providers里面注册该服务。
providers: [
{ provide: NZ_I18N, useValue: zh_CN },
EnvServiceProvider
]
6 组件中使用
引入env.service
import { Environment } from 'src/app/services/env/env.service';
constructor(
public env: Environment
) { }
ngOnInit() {
this.installation = this.env.installation;
}
7 总结
有些内容出于项目原因不能贴出来,完全按照以上的步骤写可能会有部分小问题,但这个解决办法的总体思路是这样的,希望对你有所帮助。