From 938f719f795b502e55b26ec915cb35d67215b6ac Mon Sep 17 00:00:00 2001 From: Evan Wallace Date: Fri, 9 Apr 2021 01:37:44 -0700 Subject: [PATCH] fix #1125: bug splitting + css/js + dynamic import --- CHANGELOG.md | 6 ++++++ internal/bundler/linker.go | 13 ++++++++++++- scripts/end-to-end-tests.js | 20 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 371b6b07c2c..3c10a4c5583 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +* Fix incorrect chunk reference with code splitting, css, and dynamic imports ([#1125](https://github.com/evanw/esbuild/issues/1125)) + + This release fixes a bug where when you use code splitting, CSS imports in JS, and dynamic imports all combined, the dynamic import incorrectly references the sibling CSS chunk for the dynamic import instead of the primary JS chunk. In this scenario the entry point file corresponds to two different output chunks (one for CSS and one for JS) and the wrong chunk was being picked. This bug has been fixed. + ## 0.11.6 * Fix an incorrect minification transformation ([#1121](https://github.com/evanw/esbuild/issues/1121)) diff --git a/internal/bundler/linker.go b/internal/bundler/linker.go index 594adae1bc0..b4482bfc0f4 100644 --- a/internal/bundler/linker.go +++ b/internal/bundler/linker.go @@ -2926,7 +2926,18 @@ func (c *linkerContext) computeChunks() []chunkInfo { // to look up the path for this chunk to use with the import. for chunkIndex, chunk := range sortedChunks { if chunk.isEntryPoint { - c.files[chunk.sourceIndex].entryPointChunkIndex = uint32(chunkIndex) + file := &c.files[chunk.sourceIndex] + + // JS entry points that import CSS files generate two chunks, a JS chunk + // and a CSS chunk. Don't link the CSS chunk to the JS file since the CSS + // chunk is secondary (the JS chunk is primary). + if _, ok := chunk.chunkRepr.(*chunkReprCSS); ok { + if _, ok := file.repr.(*reprJS); ok { + continue + } + } + + file.entryPointChunkIndex = uint32(chunkIndex) } } diff --git a/scripts/end-to-end-tests.js b/scripts/end-to-end-tests.js index 53dc18910a9..6632885afaf 100644 --- a/scripts/end-to-end-tests.js +++ b/scripts/end-to-end-tests.js @@ -3455,6 +3455,26 @@ import './out/entry.js' `, }), + + // Code splitting with a dynamic import that imports a CSS file + // https://github.com/evanw/esbuild/issues/1125 + test(['parent.js', '--outdir=out', '--splitting', '--format=esm', '--bundle'], { + 'parent.js': ` + // This should import the primary JS chunk, not the secondary CSS chunk + await import('./child') + `, + 'child.js': ` + import './foo.css' + `, + 'foo.css': ` + body { + color: black; + } + `, + 'node.js': ` + import './out/parent.js' + `, + }), ) // Test the binary loader