parcel and global variables in js

2.2k views Asked by At

I have a simple HTML file that includes some simple javascript files. No framework, no modules. There is a main JS file and helper functions in other JS files.

When I open this as a static site, everything works. JS code in one file is able to call functions defined in another file.

When I try the parcel bundler, pointing it at the index.html file, parcel finds all my JS files and adds some stuff to the beginning, appends a hash to the filename and modifies the links in my HTML files. All great.

However, when I open this page in the browser, it turns out my code defined in one JS file is not able to see functions defined on other JS files, throwing ReferenceError: <func> is not defined. When I inspected the JS scripts included in the HTML page, the functions are indeed defined there in the global scope. How weird is that?

1

There are 1 answers

0
Uriahs Victor On

From what I noticed, when parcel is doing the transpiling it sets a few variables at the top of the file that can be used as global variables:

var globalObject =
    typeof globalThis !== 'undefined'
      ? globalThis
      : typeof self !== 'undefined'
      ? self
      : typeof window !== 'undefined'
      ? window
      : typeof global !== 'undefined'
      ? global
      : {};

If you view the file while doing parcel watch you will see that at the top of the file.

So basically if you want a variable to be global, then inside the javascript file where you're first declaring that variable, you have to set it attach it to any one of those global variables above. E.g:

global.fruit =  'Mango';

or

window.fruit = 'Mango';

fruit now becomes a global variable of the window and you can access it from the global scope in other JS files that come after the file that set the global fruit object