有没有办法让 webpack 在全局范围内执行模块?具体来说,我的用例是以下库:
https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/lib/adal.js
其中有以下代码:
var AuthenticationContext;
if (typeof module !== 'undefined' && module.exports) {
module.exports.inject = function (conf) {
return new AuthenticationContext(conf);
};
}
正如您所看到的,该模块正在导出一个注入(inject)函数(不知道为什么他们不只是导出该类)。我能够使用注入(inject)函数成功构造一个新的 AuthenticationContext 对象。但是,此库中的某些功能依赖于全局 AuthenticationContext 类,并且当 window.AuthenticationContext === 未定义时会出错。我想将此模块与 webpack 捆绑在一起,但不知何故,我需要确保 AuthenticationContext 在全局范围内可用。有什么办法可以做到这一点吗?
我已经阅读过有关 ProvidePlugin 的内容,但是据我了解,ProvidePlugin 只是采用导出的值并将其附加到全局范围。在这种情况下,我需要确保非导出值在全局范围内可用。
最明显的解决方案就是在全局范围内执行此模块。但是,我希望这个模块成为 bundle 的一部分。我怎样才能做到这一点?
提前致谢。
最佳答案
我想我用以下代码解决了这个问题:
import {inject} from 'adal-angular/lib/adal.js';
import config from './auth-config';
export default class Authenticator {
constructor() {
this.authContext = inject(config);
window.AuthenticationContext = this.authContext.constructor;
}
}
基本上,我手动公开构造函数。
关于javascript - webpack 在全局范围内执行模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36507542/