Dynamic Import in Loop
import() inside loops
warningPerformance
no-dynamic-import-loopWhy 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
lib/plugins.tsconst plugins = ["auth", "analytics", "sentry"];
for (const name of plugins) {
// Sequential dynamic imports
const mod = await import(`./plugins/${name}`);
mod.init();
}lib/plugins.tsimport * 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--jsonand 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-loopat the top of the file- How it works
- Matches text patterns. Source on GitHub