[Javascript] Import the Same JavaScript Module Multiple Times with Cache Busting

Zhentiw發表於2024-11-25

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.

// file: timeout.ts
await new Promise(res => setTimeout(res, 1000));

console.log(`Timeout done ${new Date()}`)

// file: index.ts
import "./timeout";
import "./timeout";

Run bun run index.ts, we only see the output once, even we have import the timeout.tsfile twice

Timeout done Mon Nov 25 2024 09:17:15 GMT+0200 (Eastern European Standard Time)

This is due to the caching.

If we tried to change import by using dynamic importing:

await import("./timeout");
await import("./timeout");

It still behiavor the same.

What we need to do is adding some query param:

await import(`./timeout?random=${Math.random()}`);
await import(`./timeout?random=${Math.random()}`);

Code:

// file: timeout.ts
await new Promise((res) => setTimeout(res, 1000));

const date = new Date();

export const sayHi = () => console.log(`Hi ${date.toISOString()}`);


// file: index.ts
type TimeoutModule = typeof import("./timeout");
const { sayHi }: TimeoutModule = await import(
  `./timeout?random=${Math.random()}`
);
sayHi();
const { sayHi: sayHi2 }: TimeoutModule = await import(
  `./timeout?random=${Math.random()}`
);
sayHi2();

相關文章