Skip to content

Commit

Permalink
Ref: disabling dynamic imports in CJS build (#1757)
Browse files Browse the repository at this point in the history
There is a Jest issue on handling dynamic imports that is really
annoying.
I used to apply an approach discussed in this issue:
evanw/esbuild#2651
But now I'm going to apply another approach from the same one, just by
disabling the dynamic imports for CJS, as a cleaner way (in my opinion).

https://esbuild.github.io/api/#supported
  • Loading branch information
RobinTail authored May 12, 2024
1 parent f755608 commit 8f9352b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
10 changes: 0 additions & 10 deletions src/peer-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,6 @@ export const loadPeer = async <T>(
try {
return (await import(moduleName))[moduleExport];
} catch {}
try {
return await Promise.resolve().then(
/**
* alternative way for environments that do not support dynamic imports even it's CJS compatible
* @example jest with ts-jest
* @link https://github.com/evanw/esbuild/issues/2651
*/
() => require(moduleName)[moduleExport],
);
} catch {}
throw new MissingPeerError(moduleName);
};

Expand Down
9 changes: 9 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ export default defineConfig({
dts: true,
minify: true,
esbuildOptions: (options, { format }) => {
options.supported = {};
if (format === "cjs") {
/**
* Downgrade dynamic imports for CJS even they are actually supported, but still are problematic for Jest
* @example jest with ts-jest
* @link https://github.com/evanw/esbuild/issues/2651
*/
options.supported["dynamic-import"] = false;
}
options.define = {
"process.env.TSUP_BUILD": `"v${version} (${format.toUpperCase()})"`,
};
Expand Down

0 comments on commit 8f9352b

Please sign in to comment.