我在 Webpack 构建的入口点模块中将 Angular 1.4 导入为 CommonJS 模块(即使用 var angular = require("angular");
),但不知何故它在全局中可用浏览器的命名空间(即 window.angular
)。
在 Angular 1.4 的源代码中我发现了以下几行:
(function(window, document, undefined) {'use strict';
...
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
getPrototypeOf = Object.getPrototypeOf,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
那么,我是否理解正确,在 require
上,这一行:
angular = window.angular || (window.angular = {})
检查全局 Angular 对象是否可用,如果不可用,则创建它。那么,Angular 默默地引入了副作用?
最佳答案
Angular 与全局变量以及许多其他遗留库紧密相关,这些库在某些时候没有机会作为成熟的 CJS/UMD 模块提供(以及 Angular still isn't ,截至v1.5.2)。
var
...
angular = window.angular || (window.angular = {})
等于
if (!window.angular)
window.angular = {};
var
...
angular = window.angular;
前者要小几个字节,而且要更黑客一些。
关于javascript - 当作为 CommonJS 模块加载时,Angular 是否将自身全局分配给 `window.angular`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36101119/