diff --git a/src/index.ts b/src/index.ts index b8b1409..15572e0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -139,7 +139,13 @@ Module._resolveFilename = function (request, parent, isMain, options) { && !parent?.filename.includes(nodeModulesPath) ) { const possiblePaths = tsconfigPathsMatcher(request); + for (const possiblePath of possiblePaths) { + const tsFilename = resolveTsFilename.call(this, possiblePath, parent, isMain, options); + if (tsFilename) { + return tsFilename; + } + try { return resolveFilename.call( this, @@ -152,32 +158,43 @@ Module._resolveFilename = function (request, parent, isMain, options) { } } - /** - * Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions - */ - if (parent && isTsFilePatten.test(parent.filename)) { - const tsPath = resolveTsPath(request); - - if (tsPath) { - try { - return resolveFilename.call( - this, - tsPath, - parent, - isMain, - options, - ); - } catch (error) { - const { code } = error as any; - if ( - code !== 'MODULE_NOT_FOUND' - && code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED' - ) { - throw error; - } - } - } + const tsFilename = resolveTsFilename.call(this, request, parent, isMain, options); + if (tsFilename) { + return tsFilename; } return resolveFilename.call(this, request, parent, isMain, options); }; + +/** + * Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions + */ +function resolveTsFilename( + this: ThisType, + request: string, + parent: any, + isMain: boolean, + options?: any, +) { + const tsPath = resolveTsPath(request); + + if (parent && isTsFilePatten.test(parent.filename) && tsPath) { + try { + return resolveFilename.call( + this, + tsPath, + parent, + isMain, + options, + ); + } catch (error) { + const { code } = error as any; + if ( + code !== 'MODULE_NOT_FOUND' + && code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED' + ) { + throw error; + } + } + } +} diff --git a/tests/fixtures/tsconfig/src/paths-prefix-match-js.ts b/tests/fixtures/tsconfig/src/paths-prefix-match-js.ts new file mode 100644 index 0000000..47e161c --- /dev/null +++ b/tests/fixtures/tsconfig/src/paths-prefix-match-js.ts @@ -0,0 +1,3 @@ +import value from 'p/nested-resolve-target.js'; + +console.log(value); diff --git a/tests/specs/typescript/tsconfig.ts b/tests/specs/typescript/tsconfig.ts index 317d2cb..2b26611 100644 --- a/tests/specs/typescript/tsconfig.ts +++ b/tests/specs/typescript/tsconfig.ts @@ -50,6 +50,13 @@ export default testSuite(async ({ describe }, node: NodeApis) => { expect(nodeProcess.stdout).toBe('nested-resolve-target'); }); + test('resolves paths via .js', async () => { + const nodeProcess = await node.load('./src/paths-prefix-match-js.ts', { + cwd: './tsconfig', + }); + expect(nodeProcess.stdout).toBe('nested-resolve-target'); + }); + describe('dependency', ({ test }) => { test('resolve current directory', async () => { const nodeProcess = await node.load('./dependency-resolve-current-directory', {