Search code examples
javascriptecmascript-6babel-loader

Why can we use global variable in browser?


As we know, the global variable is window in browser and global in nodejs.

I read source code about some NPM package, their use global like global.Set instead of window.Set. When I import that package, it works well in my project base on browser. It confuse me.

I think the reason is babel. Maybe use global can write cross-platform package by babel? But how it works.

package use global


Solution

  • I'm not an expert in babel nor webpack, far from it, but looking at the output code from webpack, you can see that webpack is injecting the global variant to your code if you use it, so if we have a simple code like:

    console.log("just a test");
    

    This is what ends up in our source code:

    eval("__webpack_require__.r(__webpack_exports__);\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n/* harmony default export */ __webpack_exports__[\"default\"] =
    

    But, if we would use the next code:

    console.log("just a test", global);
    

    This is our output:

    eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n/* harmony default export */ __webpack_exports__[\"default\"] =
    

    You can clearly see the change.

    Found this issue that you might find helpful in figuring this out.

    From what I understood babel is using this internally, so it exports it if you use it in the code.

    Please note that you can't access global variant in the console.

    Note global and window are the same object, it is not a copy, so all changes done to global, will be done on window