From 96bc59680c7300ab6f4f740da26fa16e1970c7c0 Mon Sep 17 00:00:00 2001 From: Hiroki Osame Date: Sat, 4 May 2024 22:57:56 +0900 Subject: [PATCH] fix(tsImport): handle importing packages (#14) --- src/esm/hook/resolve.ts | 51 +++++++++++++++++++++++------------------ tests/specs/api.ts | 12 ++++++++-- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/src/esm/hook/resolve.ts b/src/esm/hook/resolve.ts index 8a36e55b..cefb97bd 100644 --- a/src/esm/hook/resolve.ts +++ b/src/esm/hook/resolve.ts @@ -121,6 +121,35 @@ export const resolve: resolve = async ( return nextResolve(specifier, context); } + const isPath = ( + specifier.startsWith(fileProtocol) + || isRelativePathPattern.test(specifier) + ); + + // bare specifier + if (!isPath) { + // TS path alias + if ( + tsconfigPathsMatcher + && !context.parentURL?.includes('/node_modules/') + ) { + const possiblePaths = tsconfigPathsMatcher(specifier); + for (const possiblePath of possiblePaths) { + try { + return await resolve( + pathToFileURL(possiblePath).toString(), + context, + nextResolve, + ); + } catch {} + } + } + + // npm package -- use default resolution + return nextResolve(specifier, context); + } + + // Inherit namespace from parent let requestNamespace = getNamespace(specifier); if (context.parentURL) { const parentNamespace = getNamespace(context.parentURL); @@ -139,28 +168,6 @@ export const resolve: resolve = async ( return await tryDirectory(specifier, context, nextResolve); } - const isPath = ( - specifier.startsWith(fileProtocol) - || isRelativePathPattern.test(specifier) - ); - - if ( - tsconfigPathsMatcher - && !isPath // bare specifier - && !context.parentURL?.includes('/node_modules/') - ) { - const possiblePaths = tsconfigPathsMatcher(specifier); - for (const possiblePath of possiblePaths) { - try { - return await resolve( - pathToFileURL(possiblePath).toString(), - context, - nextResolve, - ); - } catch {} - } - } - // Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions // // If `allowJs` is set in `tsconfig.json`, then we'll apply the same resolution logic diff --git a/tests/specs/api.ts b/tests/specs/api.ts index 63e20152..0e330764 100644 --- a/tests/specs/api.ts +++ b/tests/specs/api.ts @@ -20,7 +20,15 @@ const tsFiles = { import { bar } from './bar.js' export const foo = \`foo \${bar}\` as string `, - 'bar.ts': 'export const bar = "bar" as string', + 'bar.ts': 'export type A = 1; export { bar } from "pkg"', + 'node_modules/pkg': { + 'package.json': JSON.stringify({ + name: 'pkg', + type: 'module', + exports: './index.js', + }), + 'index.js': 'export const bar = "bar"', + }, }; export default testSuite(({ describe }, node: NodeApis) => { @@ -244,7 +252,7 @@ export default testSuite(({ describe }, node: NodeApis) => { nodePath: node.path, nodeOptions: [], }); - expect(stdout).toBe('file.ts\nfoo.ts\nbar.ts'); + expect(stdout).toBe('file.ts\nfoo.ts\nbar.ts\nindex.js'); }); });