evanw / evanw/esbuild

ESM dynamic import to glob imports, throw synchronous error

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

Description

### Expected behavior
the transformed Import Calls should follow the ecma specification, which should be a Rejected Promise.

### current behavior:
```
const main = async () => {
const num = 1;
await import(`./file${num }`).catch(err => {
// can not capture module not fould error
});

try {
await import(`./file${num }`)
} catch (err) {
// this could
}

}
```
the transformed code:
```
var __glob = (map) => (path) => {
var fn = map[path];
if (fn) return fn();
throw new Error("Module not found in bundle: " + path); // synchronously throws an error.
};
// import("./file*") in entry.js
var globImport_file = __glob({
"./file.js": () => Promise.resolve().then(() => (init_file(), file_exports))
});
var main = async () => {
const num = 3;
await globImport_file(`./file${num}`).catch((err) => {
if (err.code === "ERR_MODULE_NOT_FOUND") {
console.log(err);
}
});
try {
await globImport_file(`./file${num}`);
} catch (err) {
}
};
```

### demo: https://esbuild.github.io/try/#YgAwLjI0LjAAIC0tYnVuZGxlAGUAZW50cnkuanMAY29uc3QgbWFpbiA9IGFzeW5jICgpID0+IHsKICAgY29uc3QgbnVtID0gMTsKICAgYXdhaXQgaW1wb3J0KGAuL2ZpbGUke251bSB9YCkuY2F0Y2goZXJyID0+IHsKICAgICAgIGlmIChlcnIuY29kZSA9PT0gIkVSUl9NT0RVTEVfTk9UX0ZPVU5EIikgewogICAgICAgICAvLyBub3Qgd29ya3MKICAgICAgIH0KICAgfSk7CgogICB0cnkgewogICAgICBhd2FpdCBpbXBvcnQoYC4vZmlsZSR7bnVtIH1gKQogICB9IGNhdGNoIChlcnIpIHsKICAgICAvLyB0aGlzIHdvcmtzCiAgIH0KCn0AAGZpbGUuanMAZXhwb3J0IGRlZmF1bHQgMTsAAGZpbGUyLmpzAGV4cG9ydCBkZWZhdWx0IDE7

### Possible Workaround:
add a new glob for dynamic import:
```
var __globImport = map => path => {
var fn = map[path]
if (fn) return fn()
return Promise.reject('Module not found')
}
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Reproduce the linked demo using entry.js with file.js and file2.js, then compare the generated dynamic-import wrapper with the ECMAScript rejected-Promise behavior described in the issue. Trace the transformation that produces __glob and verify that missing modules are handled asynchronously; done means both catch examples capture the error without a synchronous throw.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.