@fatso83/retry-dynamic-import

中文文档
2.3.0发布于 2026/10/05MITTypeScriptES Module零依赖近 30 天下载 6.8万

Retry dynamic imports using cache busting and exponential backoff

原始使用文档
文档目录12 节
  1. Why not just catch a failure and reload the page?
  2. Demo?
  3. Limitations
  4. Installing
  5. Usage
  6. Vanilla JS util
  7. Custom strategies
  8. React utility
  9. reactLazyWithRetry
  10. Contributing
  11. Publishing a patch release
  12. Packaging without publishing

Retry dynamic imports

Retry dynamic imports using cache busting and exponential backoff

npm version

Did you know that the HTML spec demands that failed dynamic import resolutions are to be cached? Turns out, most people do not and only get to know this once they deploy apps using dynamic imports to production and start seeing weird errors after some time. Neither did I, and I ended up doing a whole lot of debugging and googling after receiving mysterious bug reports from users before I found the WHATWG issue for exactly this situation. Since this has been at a stand still since 2021, I ended up creating this library to work around the issues.

This package was originally a fork of Alon Mizrahi's work, but the new code no longer uses Alon's approach, which was relying on parsing Chromium specific error messages, and the new approach works in Firefox and other browsers as well.

Completed improvements:

  • ✅ unit tests
  • ✅ support non-Chromium browsers (like Firefox)
  • ✅ tree shakeable (does not pull in React if you just use the non-react bits)
  • ✅ speed up resolution on afflicted clients by not waiting for first cache busting attempt
  • ✅ fix exports to work with Typescript using both NodeNext and "classic" module resolution
  • ❌ dual exports (currently just ESM), shout out if you want it (we already produce the *.cjs files)

Why not just catch a failure and reload the page?

While that works fine in Firefox, in Chromium based browsers (Edge, Chrome, ...) a failed module import is cached and that failure is sticky: it is not retried on reload or over browser restarts (per Chrome 113). That is real failures, not DevTool URL blocking, which is not sticky, for whatever reason.

Demo?

  1. Open the demo application that is deployed on Github Pages
  2. Open DevTools and refresh the page
  3. Right click on the ExpensiveComponent.* url and choose to block it
  4. Refresh and see the network requests fail in the Network tab of DevTools
  5. Unblock the url and see it work again

If you want to see the sticky behavior mentioned above, setup Charles Proxy and its "Breakpoints" feature to be able to selectively block or accept requests. Works great!

Limitations

Transitive imports: read this article to understand the details of how dynamic imports might fail and how this solves some of these use cases. One use case it cannot solve is if a transitive dependency should fail to load.

Installing

npm i @fatso83/retry-dynamic-import

Usage

The package has two main exports

export const dynamicImportWithRetry // default implementation with 5 retries
export const createDynamicImportWithRetry  // factory to make your own version of dynamicImportWithRetry

Vanilla JS util

Works in any framework

import { dynamicImportWithRetry } from "@fatso83/retry-dynamic-import";
const myModule = dynamicImportWithRetry(() => import("./my-module")); // this works regardless of framework, lib, etc

See the unit tests or the implementation for what options it supports.

Custom strategies

The createDynamicImportWithRetry factory recently got a new feature that allows you to pass in your own custom strategy for dealing with imports, instead of the pre-defined ones. One specific use-case, shown in the tests, is that this opens up for supporting retries of dynamic import paths.

// ONE-TIME SETUP
const moduleSpecifierSymbol = Symbol()
const lookupUsingSymbolInImporter: UrlStrategy = (_, importer) =>
    moduleSpecifierSymbol in importer
    ? String(importer[moduleSpecifierSymbol])
    : null;

const customRetryImport = createDynamicImportWithRetry(3, {strategy: lookupUsingSymbolInImporter})
// ...

// USE
// This can now be used with dynamically created paths like this
const path = readFromUser();
const importer = Object.assign(() => import(path), {
    [moduleSpecifierSymbol]: path,
});

await customRetryImport(importer)

React utility

Additionallly, you can import reactLazyWithRetry from '@fatso83/retry-dynamic-import/react-lazy' for a utility that can be used instead of React.lazy() for lazy imports with retries. In version 1.* this was exposed on root, but most bundlers were unable to tree-shake React, so I decided to make a breaking change for version 2 that exposes it as subpath export.

React is an _optional dependency of this package_, which means you can use it with Svelte or VanillaJS without pulling in extra dependencies by specifying npm install --omit=optional, but if you use the react-lazy sub-export you will of course need to have React in your dependency tree :)

reactLazyWithRetry

Thin wrapper around the above, calling out to React.lazy()

const LazyAbout = reactLazyWithRetry(() => import("./components/About"));
const LazyHome = reactLazyWithRetry(() => import("./components/Home"));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/" element={<LazyHome />} />
        <Route path="/about" element={<LazyAbout />} />
      </Routes>
    </Suspense>
  </Router>
);

Contributing

Please do!

  • Run tests: DEBUG=dynamic-import:* npm t -- --watch (the env var is just for verbose output)

Publishing a patch release

With all changes committed on main and npm authentication configured, run:

npm version patch

This is the complete release command. The preversion hook installs the demo and consumer dependencies from their lockfiles with npm ci, then runs unit tests, builds, consumer tests and packed-package checks. npm increments the version and creates a version commit and tag. The postversion hook rebuilds with the new version, validates the actual tarball, publishes that tarball to npm, updates the demo on GitHub Pages, and pushes the branches and tags.

If npm authentication is missing or expired, run npm login first. npm may also ask you to authenticate the publish operation.

Do not run a separate npm publish from the source checkout. The release command publishes the validated package from pkg/ instead.

Packaging without publishing

Use npm run pack:release to build and create a validated tarball in pkg/ without publishing it or changing the version.

To run the checks individually: npm test, npm run build, npm run test-consumers, and npm run test:package. The package test installs the actual .tgz into a temporary consumer and verifies runtime exports, TypeScript imports, and retry behavior after Vite's default production minification. Packing or publishing directly from the source checkout is rejected because its advertised entry files exist only in pkg/ after the build.

版本与发布记录

@fatso83/retry-dynamic-import 共发布 25 个版本,首次发布于 2023/05/10;过去 12 个月发布了 2 个版本。

版本发布日期距今
2.3.0latest2026/10/051 个月前
2.2.12026/10/011 个月前
2.2.02025/09/081.2 年前
2.1.42025/03/261.6 年前
2.1.32025/03/131.7 年前
2.1.22025/03/131.7 年前

关于 @fatso83/retry-dynamic-import 的常见问题

@fatso83/retry-dynamic-import 是什么?

Retry dynamic imports using cache busting and exponential backoff

如何安装 @fatso83/retry-dynamic-import?

在项目目录运行 npm install @fatso83/retry-dynamic-import,或使用 pnpm add / yarn add / bun add。

@fatso83/retry-dynamic-import 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fatso83/retry-dynamic-import 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@fatso83/retry-dynamic-import 可以商用吗?

@fatso83/retry-dynamic-import 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fatso83/retry-dynamic-import 的下载量有多少?

根据 npm 官方下载统计,@fatso83/retry-dynamic-import 在 2026/10/15 – 2026/11/13 这 30 天内被下载 68,478 次,日均约 2,283 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fatso83/retry-dynamic-import 还在维护吗?

最新版本 2.3.0 发布于 2026/10/05(1 个月前);至今共发布 25 个版本,其中过去 12 个月发布了 2 个;首次发布于 2023/05/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。