Dynamic Import in Loop

import() inside loops

warningPerformanceno-dynamic-import-loop

Why this matters

A dynamic import() inside a loop loads modules one after another: each iteration waits for the one before it. For ten plugins that's ten sequential loads where one would do.

Example

Flaggedlib/plugins.ts
const plugins = ["auth", "analytics", "sentry"];
for (const name of plugins) {
  // Sequential dynamic imports
  const mod = await import(`./plugins/${name}`);
  mod.init();
}
Fixedlib/plugins.ts
import * as auth from "./plugins/auth";
import * as analytics from "./plugins/analytics";
import * as sentry from "./plugins/sentry";

for (const plugin of [auth, analytics, sentry]) {
  plugin.init();
}

How to fix

Import the modules statically when the list is known. If it has to be dynamic, load them once, before the loop, and reuse the result.

Reference

In the output
Findings carry "ruleId": "no-dynamic-import-loop" in --json and the same id in SARIF and in the terminal.
Silence one line
// prodlint-disable-next-line no-dynamic-import-loop
Silence a whole file
// prodlint-disable no-dynamic-import-loop at the top of the file
How it works
Matches text patterns. Source on GitHub