JavaScript import statements running code

582 Views Asked by At

I'm trying to diagnose a problem thats recently arisen for us, after upgrading our suppported browser (~40 -> ~60)

We have this effective code in an external (now unsupported) library, that sits in an iffe:

(function(window, undefined){
    # external library
    if(!window.terribleIdea){
        window.terribleIdea = {}
    }
    <some code>
    if(!window.terribleIdea.config.url){
        window.terribleIdea.config.url = 'the wrong url'
    }

    localStorage.set('somethingImportant', getStuff(window.terribleIdea.config.url))
})( window );

Now we did have a bootstap type file that looked like this:

# appBootstrapper.js
import applyConfig from './app/configApplier';
import ALL_ANGULAR_MODULES from './app'; # contains angular.module set up for 
                                         # app and every dependency

fetchConfig()
    .then(applyConfig)
    .then () => angular.bootstrap(document, [ALL_ANGULAR_MODULES])
    .catch( error => {
        alert(`It borked:  ${error.message}`)
    });

Amongst other things applyConfig does:

window.terribleIdea = {
    config: {
        url: 'not terrible'
    }
}

What now happens, is that the import statement of ALL_ANGULAR_MODULES ends up running the code in the external library, and setting local storage. What we think used to happen is that it was only called on angular.bootstrap running.

Now what I need to find out is, has the functionality of the import statement changed in a later version of chrome, or has it always been running this code and gone unnoticed?

All I can find is references to Dynamic Imports, and the order of scripts running, in <script></script> tags.

1

There are 1 best solutions below

0
On BEST ANSWER

It is hard to debug without access to the project (see discussion in comments above). Here are some possibilities worth exploring while encountering such issues. It is of course possible that it was like this all along.

  • Change in the bundler configuration. Webpack accepts entries as arrays, and order matters in them.
  • Change in the way the bundler/dependency manager reacts to dynamic imports
  • Change in the way your application loads its dependency during the its bootstrap phase. It is not (imo) angular specific, as many app use some kind of "componentization" which translates in files executed in a different order they are imported (as they may only export constructors or whatnot).