Package · PKG0004
Guard import() of optional packages with try or .catch()
Find import() calls of optional peers and optional dependencies that no try block in the same function and no .catch() handles, in runtime JavaScript reachable from a package export.
package/optional-peer-import-in-trysrc/rule-packs/package/rules/optional-peer-import-in-try.ts Upstream docs Run this rule
pnpm vite-doctor . --extends package/recommended --rules package/optional-peer-import-in-try
Why it matters
esbuild, and the Wrangler, Netlify, and Vite builds that use it, fails the consumer's build when an import() names a package that is not installed. It keeps the import for run time only when the import() is directly awaited in a try body of the same function or has a .catch() or two-argument .then(). A try in a caller, or a loader callback passed to a helper that catches, does not count.
Recommended fix
Directly await the import() of the optional package inside a try in the function that calls it, and turn a missing package into an error that names the install command. A .catch() on the import() also works.
Useful links
Example
Keep the import() of an optional peer inside the try
Before
export const loadForge = () => importOptional(() => import("forge"), "forge");
After
export async function loadForge() {
try {
return await import("forge");
} catch (error) {
throw new Error("Install forge to use this integration", { cause: error });
}
}