【问题标题】:using webpack 2 DefinePlugin with angular-cli based project将 webpack 2 DefinePlugin 与基于 angular-cli 的项目一起使用
【发布时间】:2026-01-02 08:50:02
【问题描述】:

我正在尝试将带有 webpack2 项目的 angular2 转换为基于 angular-cli 的项目。

如果我理解正确的话,angular-cli 现在支持 webpack。在我原来的项目中,我注入了以下app.config.js

module.exports =  {
    webServer: {
        appBaseHref : JSON.stringify("/")
    },
    auth0: {
        apiKey: JSON.stringify("API_KEY"),
        domain: JSON.stringify("DOMAIN.auth0.com"),
        callbackUrl: JSON.stringify("CALLBACK_URL")
    }
};

通过将以下内容添加到webpack.config.js 文件:

const appConfig = require("./config/app.config");
const DefinePlugin = require("webpack/lib/DefinePlugin");
...
module.exports = {
    plugins: [
       new DefinePlugin({
           APP_CONFIG: appConfig
       }),
...

然后在我的打字稿项目中,我会用declare var APP_CONFIG:any; 声明APP_CONFIG,然后我会使用它的属性。如何在 angular-cli 项目中注入这样的对象?

谢谢

【问题讨论】:

  • 你不能为此做一个服务吗?
  • @Chrillewoodz - 是的.. 我可以.. 试图弄清楚为什么我首先使用 webpack 这样做但我什么也没得到:) 我该怎么办?你想把它作为答案发布吗?我要删除这个问题吗?
  • 给我一分钟。
  • 所以我想要同样的东西 - 这样我就可以注入内部版本号。不确定服务答案是否适合我。我想要一个像 APP_VERSION 这样的全局变量并将其设置为 childProcess.execSync('git rev-list HEAD --count').toString();

标签: angular webpack angular-cli webpack-2


【解决方案1】:

这是一个简单的示例,它仅使用带有setget 方法的普通服务:

import {Injectable} from '@angular/core';

@Injectable()

export class AppConfigService {

  public config: any = {
    apiKey: '[api_key]',
    domain: '[domain]',
    callbackUrl: '[callbackUrl]'
  }

  constructor() {}

  /* Allows you to update any of the values dynamically */
  set(k: string, v: any): void {
    this.config[k] = v;
  }

  /* Returns the entire config object or just one value if key is provided */
  get(k: string): any {
    return k ? this.config[k] : this.config;
  }
}

对于更复杂的用例,您可能希望将其转换为可观察对象,但我认为在这种简单的情况下没有必要。

【讨论】:

    最近更新 更多