将 webpack 2 DefinePlugin 与基于 angular-cli 的项目一起使用
using webpack 2 DefinePlugin with angular-cli based project
我正在尝试将带有 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 项目中注入这样的对象?
谢谢
这是一个简单的示例,它仅使用具有 set
和 get
方法的普通服务:
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;
}
}
对于更复杂的用例,您可能希望将其转换为可观察对象,但我认为在这种简单的情况下没有必要这样做。
我正在尝试将带有 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 项目中注入这样的对象?
谢谢
这是一个简单的示例,它仅使用具有 set
和 get
方法的普通服务:
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;
}
}
对于更复杂的用例,您可能希望将其转换为可观察对象,但我认为在这种简单的情况下没有必要这样做。