evanw / evanw/esbuild

[Feature Request] Skip resolving dependencies that are `require`d inside a try/catch if the resolver throws a `MODULE_NOT_FOUND` error

Open
#1,127 2 comments 10 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
40.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

When a `require` call is inside a try/catch (e.g.
```ts
try {
require(`dep`);
} catch {
}
```
), ESBuild's default resolver treats it as external and doesn't try to resolve it. This changes when I add a plugin that registers `onResolve`, as ESBuild will forward the `require` call to the resolver. The problem is that the resolver loses the context of the `require` call and always tries to resolve it (throwing a `MODULE_NOT_FOUND` error if it can't be resolved), even if the `require` call is inside a try/catch.

My suggestion would be to check if the error thrown has `error.code === 'MODULE_NOT_FOUND'` and skip it if the `require` call is inside a try/catch.

An alternative would be to add a new `args.optional` property on the resolve args so that resolver plugins can manually skip the dependency if the resolution fails.

Use case: I want to make `@yarnpkg/esbuild-plugin-pnp` not throw when optional peer dependencies that are `require`d inside a try/catch are not provided by the parent (https://github.com/yarnpkg/berry/pull/2717/checks?check_run_id=2292511030#step:4:177).

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by tracing how require calls inside try/catch are passed to onResolve plugins and how resolver failures expose error.code. Compare the MODULE_NOT_FOUND case with the proposed optional resolve context, then verify that missing optional dependencies remain skipped while other resolution errors still surface.

Written by the indexing model from the issue text.

Assessment

Tech stack
go, javascript
Domain
build-system, compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.