From 48f0a7552fb6743fa06b63f6f600a9af95cb19f9 Mon Sep 17 00:00:00 2001 From: Hiroki Osame Date: Sat, 11 May 2024 01:01:40 +0900 Subject: [PATCH] fix(tsImport): import module from commonjs --- src/esm/hook/utils.ts | 2 +- src/utils/transform/get-esbuild-options.ts | 2 +- tests/specs/api.ts | 20 ++++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/esm/hook/utils.ts b/src/esm/hook/utils.ts index e7cee7ff2..37403600e 100644 --- a/src/esm/hook/utils.ts +++ b/src/esm/hook/utils.ts @@ -28,7 +28,7 @@ export const tsExtensionsPattern = /\.([cm]?ts|[tj]sx)($|\?)/; export const isJsonPattern = /\.json(?:$|\?)/; const getFormatFromExtension = (fileUrl: string): ModuleFormat | undefined => { - const extension = path.extname(fileUrl); + const extension = path.extname(fileUrl.split('?')[0]); if (extension === '.json') { return 'json'; diff --git a/src/utils/transform/get-esbuild-options.ts b/src/utils/transform/get-esbuild-options.ts index 58f872ab0..1441d9add 100644 --- a/src/utils/transform/get-esbuild-options.ts +++ b/src/utils/transform/get-esbuild-options.ts @@ -48,7 +48,7 @@ export const patchOptions = ( const originalSourcefile = options.sourcefile; if (originalSourcefile) { - const extension = path.extname(originalSourcefile); + const extension = path.extname(originalSourcefile.split('?')[0]); if (extension) { // https://github.com/evanw/esbuild/issues/1932 diff --git a/tests/specs/api.ts b/tests/specs/api.ts index 456672a32..bedd5e810 100644 --- a/tests/specs/api.ts +++ b/tests/specs/api.ts @@ -324,6 +324,26 @@ export default testSuite(({ describe }, node: NodeApis) => { expect(stdout).toBe('Fails as expected 1\nfoo bar\nfoo bar\nFails as expected 2'); }); + test('mts from commonjs', async () => { + await using fixture = await createFixture({ + 'import.cjs': ` + const { tsImport } = require(${JSON.stringify(tsxEsmApiCjsPath)}); + + (async () => { + const { message } = await tsImport('./file.mts', __filename); + console.log(message); + })(); + `, + 'file.mts': 'export const message = "foo bar"', + }); + + const { stdout } = await execaNode(fixture.getPath('import.cjs'), [], { + nodePath: node.path, + nodeOptions: [], + }); + expect(stdout).toBe('foo bar'); + }); + test('namespace allows async nested calls', async () => { await using fixture = await createFixture({ 'package.json': JSON.stringify({ type: 'module' }),