[Javascript] 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.
// 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.ts
file 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();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-11-25 [Typescript] 116. Hard - Split
2022-11-25 [Typescript] 115. Hard - Drop String
2019-11-25 [ARIA] aria-describedby & aria-labelledby
2019-11-25 [Security] Always use parameterized queries
2016-11-25 [Ramda] Handle Branching Logic with Ramda's Conditional Functions
2016-11-25 [Angular2 Router] Setup page title with Router events
2015-11-25 [Redux] Store Methods: getState(), dispatch(), and subscribe()