Incorrect import order with code splitting and multiple entry points
- Dominant language
- Go
- Stars
- 40.1k
- Forks
- 1.3k
- PR merge metrics
- No merged PRs in 30d
Description
For the workaround, see https://github.com/evanw/esbuild/issues/399#issuecomment-1458680887.
---
Consider the following code:
```js
// entry1.js
import "./init-dep-1.js";
import "./run-dep.js";
// entry2.js
import "./init-dep-2.js";
import "./run-dep.js";
// init-dep-1.js
global.foo = {
log: () => console.log("foo.log() (from entry 1) called"),
};
// init-dep-2.js
global.foo = {
log: () => console.log("foo.log() (from entry 2) called"),
};
// run-dep.js
global.foo.log();
```
When you bundle this code with `esbuild --bundle --outdir=build --format=esm --splitting --platform=node --out-extension:.js=.mjs ./entry1.js ./entry2.js`, ESBuild discovers that `run-dep.js` is a module shared between both entry points. Because code splitting is enabled, ESBuild moves it into a separate chunk:
```js
// build/entry1.js
import "./chunk.P2RPFHF3.js";
global.foo = {
log: () => console.log("foo.log() (from entry 1) called")
};
```
However, by doing so, ESBuild puts `run-dep.js` above the `init-dep-1.js` or `init-dep-2.js` code. This changes the import order – and breaks the code:
```sh
$ esbuild --bundle --outdir=build --format=esm --splitting --platform=node --out-extension:.js=.mjs ./entry1.js ./entry2.js
$ node build/entry1.mjs
global.foo.log();
^
TypeError: Cannot read property 'log' of undefined
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Read the linked workaround comment, then reproduce the issue with entry1.js, entry2.js, init-dep-1.js, init-dep-2.js, and run-dep.js using the esbuild command shown. Run node on the generated entry1.mjs and verify that code splitting preserves initialization before the shared run-dep.js code so the example no longer fails.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go, javascript
- Domain
- build-system, compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100