From aa2b639a9bac8ae28a46b847013fda7f5cd4466b Mon Sep 17 00:00:00 2001 From: Hiroki Osame Date: Mon, 3 Jun 2024 12:54:21 +0900 Subject: [PATCH] fix(cjs): esm interop in `.mjs` files (#32) fixes https://github.com/privatenumber/tsx/issues/334 --- src/utils/transform/get-esbuild-options.ts | 2 ++ tests/fixtures.ts | 22 ++++++++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/utils/transform/get-esbuild-options.ts b/src/utils/transform/get-esbuild-options.ts index ec76597d2..a9d6d44c4 100644 --- a/src/utils/transform/get-esbuild-options.ts +++ b/src/utils/transform/get-esbuild-options.ts @@ -54,6 +54,8 @@ export const patchOptions = ( // https://github.com/evanw/esbuild/issues/1932 if (extension === '.cts' || extension === '.mts') { options.sourcefile = `${originalSourcefile.slice(0, -3)}ts`; + } else if (extension === '.mjs') { // only used by CJS loader + options.sourcefile = `${originalSourcefile.slice(0, -3)}js`; } } else { // esbuild errors to detect loader when a file doesn't have an extension diff --git a/tests/fixtures.ts b/tests/fixtures.ts index cdb8969a0..f5b33919f 100644 --- a/tests/fixtures.ts +++ b/tests/fixtures.ts @@ -149,14 +149,20 @@ export const files = { exports.named = 'named'; `, - 'mjs/index.mjs': outdent` - import assert from 'assert'; - export const mjsHasCjsContext = ${cjsContextCheck}; - - import ('pkg-commonjs').then((m) => assert( - !(typeof m.default === 'object' && ('default' in m.default)), - )); - `, + mjs: { + 'index.mjs': outdent` + import assert from 'assert'; + import value from './value.mjs'; + export const mjsHasCjsContext = ${cjsContextCheck}; + + assert(value === 1, 'wrong default export'); + + import ('pkg-commonjs').then((m) => assert( + !(typeof m.default === 'object' && ('default' in m.default)), + )); + `, + 'value.mjs': 'export default 1', + }, 'ts/index.ts': sourcemap.tag` import assert from 'assert';