我通过Webpack将Typescript项目捆绑为UMD模块。当我在单独的节点应用程序中导入这样的模块时,该应用程序失败并显示:
ReferenceError: window is not defined
并非我的webpack输出globalObject
已经是this
。令人讨厌的代码如下:
/***/ "./node_modules/atob/browser-atob.js":
/*!*******************************************!*\
!*** ./node_modules/atob/browser-atob.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer, module) {(function (w) {
"use strict";
function findBest(atobNative) {
// normal window
if ('function' === typeof atobNative) { return atobNative; }
// browserify (web worker)
if ('function' === typeof Buffer) {
return function atobBrowserify(a) {
//!! Deliberately using an API that's deprecated in node.js because
//!! this file is for browsers and we expect them to cope with it.
//!! Discussion: github.com/node-browser-compat/atob/pull/9
return new Buffer(a, 'base64').toString('binary');
};
}
// ios web worker with base64js
if ('object' === typeof w.base64js) {
// bufferToBinaryString
// https://git.coolaj86.com/coolaj86/unibabel.js/blob/master/index.js#L50
return function atobWebWorker_iOS(a) {
var buf = w.base64js.b64ToByteArray(a);
return Array.prototype.map.call(buf, function (ch) {
return String.fromCharCode(ch);
}).join('');
};
}
return function () {
// ios web worker without base64js
throw new Error("You're probably in an old browser or an iOS webworker." +
" It might help to include beatgammit's base64-js.");
};
}
var atobBest = findBest(w.atob);
w.atob = atobBest;
if ((typeof module === 'object') && module && module.exports) {
module.exports = atobBest;
}
}(window));
为什么Webpack捆绑了browser-atob.js而不是node-atob.js?
答案 0 :(得分:0)
我们遇到了同样的问题,对我们来说,这与我们对以下内容的依赖有关:
https://git.coolaj86.com/coolaj86/atob.js/src/branch/master/browser-atob.js
如果您不直接依赖于此,请检查您的依赖项中是否没有依赖项:)
作为解决方法,我们使用(在coffeescript中):
if process?
# for node case
atob = (input) -> Buffer.from(input, 'base64').toString('binary')
btoa = (input) -> Buffer.from(input).toString('base64')
else
# for browser/webworker
atob = self.atob
btoa = self.btoa
应该适用于节点,浏览器和Webworker案例。在JS中:
if (typeof process !== "undefined" && process !== null) {
// for node case
atob = function(input) {
return Buffer.from(input, 'base64').toString('binary');
};
btoa = function(input) {
return Buffer.from(input).toString('base64');
};
} else {
// for browser/webworker
atob = self.atob;
btoa = self.btoa;
}