2

I'm importing Angular 1.4 in my entry point module of Webpack build as a CommonJS module (i.e. with var angular = require("angular");), but somehow it becomes available in global namespace of the browser (i.e. as window.angular).

In the source code of Angular 1.4 I found the following lines:

(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;

So, do I get it right, that upon require, this line:

angular           = window.angular || (window.angular = {})

checks, if global angular object is available and if it is not, creates it. So, angular silently introduces side-effect?

Boris Burkov
  • 13,420
  • 17
  • 74
  • 109

1 Answers1

2

Angular is strongly tied to global variables, as well as a bunch of other legacy libraries that didn't have a chance to become available as full-grown CJS/UMD modules at some point (and Angular still isn't, as of v1.5.2).

var
...
angular           = window.angular || (window.angular = {})

is equal to

if (!window.angular)
  window.angular = {};

var
...
angular           = window.angular;

The former is several bytes smaller and a couple of dans hackier.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565