Import the Same JavaScript Module Multiple Times with Cache Busting

When attempting to load the same module twice in JavaScript you'll hit a cache and code won't re-run. In scenarios where you actually do want to have state in your modules, you'll have to use a cache-busting technique by passing a query parameter to a dynamic import. This lesson walks through how to add a query parameter, how to add the appropriate types for loading dynamic modules in TypeScript, and when these techniques are valuable.

Share with a coworker

Social Share Links

Transcript

[00:00] My timeout file is just a timer that resolves, and if I import it and then run it you'll see the timeout complete. Now if I try and import it again and then run it you'll see it only happens once still, even though there is actual top level code here that you might expect to execute. Now my first thought would be that instead of importing, the standard way that I could await import and load these dynamically, but we still hit the cache and we run into the same issue where it only loads this module once. So the workaround here is to add a query parameter and we'll just toss in a random number. We'll accept that and then also let it happen there.

[00:41] And then once we run this again you can see this happens twice. So one tick, two ticks, loading the same module two separate times. Now if you're also going to export something from this file, we'll just export a function that says sayHi and then I try and reference that. You'll see that TypeScript doesn't know what to do with this. Say hi is just any.

[01:04] And that's because now this is a dynamic string and we'll have to cast this to the module we're loading. So let's do this by as typeof and then I'll accept the suggestion. And so now this is cast as type of import timeout. I'm going to extract this just to clean this up a little bit. And we'll say type timeout module, accept those.

[01:28] And it's even my preference here to move this to the front so that now sayHi is cast to a function. And we can type this as well. Then once we run these you'll see our timeout is done, logsHi, timeout is done, logsHi. And let's just go ahead and set a variable here we'll call this date so that we can do something to the inside of this function which makes this a little bit more useful. So remove this and now once we load these You'll see we have high at this time and high at this time, loading the same module two separate times and then invoking a function.

[02:07] Please be very careful with loading the same module multiple times. This is treating code as data where you're expecting the module to have state, whether it's for tools for hot module reloading or some sort of A-B testing, where you want a module to behave in different ways for different scenarios. But just be aware that using the query parameter here can serve as sort of a cache buster when loading modules.