Skip to content

Commit

Permalink
feat: enable dynamic-imports by default (#361)
Browse files Browse the repository at this point in the history
Co-authored-by: Hiroki Osame <hiroki.osame@gmail.com>
  • Loading branch information
neoGeneva and privatenumber committed Mar 8, 2024
1 parent 58d5573 commit 7b948ef
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ async function ESBuildLoader(
}
}

/**
* Enable dynamic import by default to support code splitting in Webpack
*/
transformOptions.supported = {
'dynamic-import': true,
...transformOptions.supported,
};

try {
const { code, map } = await transform(source, transformOptions);
done(null, code, map && JSON.parse(map));
Expand Down
51 changes: 51 additions & 0 deletions tests/specs/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,5 +407,56 @@ export default testSuite(({ describe }, webpack: typeof webpack4 | typeof webpac
const code = built.fs.readFileSync('/dist/index.js', 'utf8');
expect(code).toContain('div{color:red}');
});

test('Keeps dynamic imports by default', async () => {
const built = await build(
{
'/src/index.js': 'export default async () => (await import("./test2.js")).default',
'/src/test2.js': 'export default "test2"',
},
(config) => {
configureEsbuildLoader(config, { options: { target: 'chrome52' } });
},
webpack,
);

expect(built.stats.hasWarnings()).toBe(false);
expect(built.stats.hasErrors()).toBe(false);

const { assets } = built.stats.compilation;
expect(assets).toHaveProperty(['index.js']);

// Chunk split because esbuild preserved the dynamic import
expect(Object.keys(assets).length).toBe(2);
expect(await built.require('/dist')()).toBe('test2');
});

test('Dynamic imports can be disabled', async () => {
const built = await build(
{
'/src/index.js': 'export default async () => (await import("./test2.js")).default',
'/src/test2.js': 'export default "test2"',
},
(config) => {
configureEsbuildLoader(config, {
options: {
target: 'chrome52',
supported: { 'dynamic-import': false },
},
});
},
webpack,
);

expect(built.stats.hasWarnings()).toBe(false);
expect(built.stats.hasErrors()).toBe(false);

const { assets } = built.stats.compilation;
expect(assets).toHaveProperty(['index.js']);

// No chunk split because esbuild removed the dynamic import
expect(Object.keys(assets).length).toBe(1);
expect(await built.require('/dist')()).toBe('test2');
});
});
});

0 comments on commit 7b948ef

Please sign in to comment.