繁体   English   中英

在 Angular 项目中的生产构建中加载全局变量的问题

[英]Problem with Loading Global Variable in Production Build In Angular Project

尝试从js文件加载环境到具有动态环境,独立于基于本文的构建。

env.js文件添加到项目中,如下所示:

(function (window) {
  window.__env = window.__env || {};

  // API url
  window.__env.apiUrl = 'http://dev.your-api.com';

  // Whether or not to enable debug mode
  // Setting this to false will disable console output
  window.__env.enableDebug = true;
}(this));

然后我将脚本添加到 index.html 以加载 js 文件:

<script src="env.js"></script>

我这样使用全局变量:

console.log(window['__env']);

我为项目提供服务,一切正常,我构建项目(使用ng build常规ng build )也一切正常,

但是当我使用ng build --prod ,全局变量为空,

如何告诉 webpack 有一个全局变量,您应该在不使用服务的情况下将其引入?

任何的想法?

我使用 JSON 文件读取 Environment 动态构建独立:

这行在 APP_Initilizer 内的 AppModule 中加载 env.json:

export function init_app(appLoadService: AppInitService) {
  return () => appLoadService.init("assets/env.json");
} 

注意:不要忘记提供部分:

  providers: [
    EnvServiceProvider,
    AppInitService,
    AuthenticationService,
    // TabGuard,
    {
      provide: APP_INITIALIZER,
      useFactory: init_app,
      deps: [AppInitService],
      multi: true,
    }
    // ...
    ]

应用初始化服务:

@Injectable({
  providedIn: 'root'
})
export class AppInitService {

  // This is the method you want to call at bootstrap
  // Important: It should return a Promise
  public init(path:string) {
    return from(
        fetch(path).then(function(response) {
          return response.json();
        })
      ).pipe(
        map((config) => {
        window['__env'] = config;
        return
      })).toPromise();
  }
} 

然后使用环境提供程序提供 envs:

import { EnvService } from './env.service';

export const EnvServiceFactory = () => {
  // Create env
  const env = new EnvService();

  // Read environment variables from browser window
  const browserWindow = window || {};
  const browserWindowEnv = browserWindow['__env'] || {};

  // Assign environment variables from browser window to env
  // In the current implementation, properties from env.js overwrite defaults from the EnvService.
  // If needed, a deep merge can be performed here to merge properties instead of overwriting them.
  for (const key in browserWindowEnv) {
    if (browserWindowEnv.hasOwnProperty(key)) {
      env[key] = window['__env'][key];
    }
  }
  return env;
};

export const EnvServiceProvider = {
  provide: EnvService,
  useFactory: EnvServiceFactory,
  deps: [],
};

像这样使用 env 提供程序:

  env: any;
  constructor(
    public envService: EnvService
  ) {
    this.env = this.envService;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM