diff --git a/src/paths-matcher/index.ts b/src/paths-matcher/index.ts index 65634fd..7756c25 100644 --- a/src/paths-matcher/index.ts +++ b/src/paths-matcher/index.ts @@ -1,6 +1,6 @@ import path from 'path'; import slash from 'slash'; -import type { TsConfigResult } from '../types.js'; +import type { MatchOptions, TsConfigResult } from '../types.js'; import { isRelativePathPattern } from '../utils/is-relative-path-pattern.js'; import { implicitBaseUrlSymbol } from '../utils/symbols.js'; import { @@ -40,6 +40,7 @@ const parsePaths = ( */ export const createPathsMatcher = ( tsconfig: TsConfigResult, + { fallback = true }: MatchOptions = {}, ) => { if (!tsconfig.config.compilerOptions) { return null; @@ -97,7 +98,7 @@ export const createPathsMatcher = ( if (!matchedValue) { return ( - baseUrl + (baseUrl && fallback) ? [slash(path.join(resolvedBaseUrl, specifier))] : [] ); diff --git a/src/types.ts b/src/types.ts index e9a172d..e4e27be 100644 --- a/src/types.ts +++ b/src/types.ts @@ -15,3 +15,12 @@ export type TsConfigResult = { */ config: TsConfigJsonResolved; }; + +export type MatchOptions = { + /** + * Fallback to joined path. + * @description Return `path.join(baseUrl, specifier)` if the specifier matches nothing + * @default true + */ + fallback?: boolean; +} diff --git a/tests/specs/create-paths-matcher.ts b/tests/specs/create-paths-matcher.ts index 205b587..7a6fe41 100644 --- a/tests/specs/create-paths-matcher.ts +++ b/tests/specs/create-paths-matcher.ts @@ -427,6 +427,38 @@ export default testSuite(({ describe }) => { await fixture.rm(); }); + test('fallback option', async () => { + const fixture = await createFixture({ + 'tsconfig.json': createTsconfigJson({ + compilerOptions: { + baseUrl: '.', + paths: { + '@match': ['./match'], + }, + }, + }), + }); + + const tsconfig = getTsconfig(fixture.path); + expect(tsconfig).not.toBeNull(); + + const fallbackmatcher = createPathsMatcher(tsconfig!, { fallback: true })!; + const doesntfallbackmatcher = createPathsMatcher(tsconfig!, { fallback: false })!; + expect(doesntfallbackmatcher('@mismatch')).toStrictEqual([]); + const resolvedAttempts = await getTscResolution('@match', fixture.path); + expect([fallbackmatcher('@match'), doesntfallbackmatcher('@match')]) + .toStrictEqual(Array.from({ length: 2 }).fill([ + resolvedAttempts[0].filePath.slice(0, -3), + ])); + const mismatchResult = await getTscResolution('@mismatch', fixture.path); + + expect(fallbackmatcher('@mismatch')).toStrictEqual([ + mismatchResult[0].filePath.slice(0, -3), + ]); + + await fixture.rm(); + }); + test('matches absolute paths', async () => { const fixture = await createFixture({ 'tsconfig.json': createTsconfigJson({