Skip to content

Commit 3e42d9d

Browse files
committed
feat: add fallback option to avoid meaningless result.
1 parent 33d4f81 commit 3e42d9d

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

src/paths-matcher/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import path from 'path';
22
import slash from 'slash';
3-
import type { TsConfigResult } from '../types.js';
3+
import type { MatchOptions, TsConfigResult } from '../types.js';
44
import { isRelativePathPattern } from '../utils/is-relative-path-pattern.js';
55
import { implicitBaseUrlSymbol } from '../utils/symbols.js';
66
import {
@@ -40,6 +40,7 @@ const parsePaths = (
4040
*/
4141
export const createPathsMatcher = (
4242
tsconfig: TsConfigResult,
43+
{ fallback = true }: MatchOptions = {},
4344
) => {
4445
if (!tsconfig.config.compilerOptions) {
4546
return null;
@@ -97,7 +98,7 @@ export const createPathsMatcher = (
9798

9899
if (!matchedValue) {
99100
return (
100-
baseUrl
101+
(baseUrl && fallback)
101102
? [slash(path.join(resolvedBaseUrl, specifier))]
102103
: []
103104
);

src/types.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,12 @@ export type TsConfigResult = {
1515
*/
1616
config: TsConfigJsonResolved;
1717
};
18+
19+
export type MatchOptions = {
20+
/**
21+
* Fallback to joined path.
22+
* @description Return `path.join(baseUrl, specifier)` if the specifier matches nothing
23+
* @default true
24+
*/
25+
fallback?: boolean;
26+
}

tests/specs/create-paths-matcher.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,32 @@ export default testSuite(({ describe }) => {
427427
await fixture.rm();
428428
});
429429

430+
test('fallback option', async () => {
431+
const fixture = await createFixture({
432+
'tsconfig.json': createTsconfigJson({
433+
compilerOptions: {
434+
paths: {
435+
'@test': ['./test'],
436+
},
437+
},
438+
}),
439+
});
440+
441+
const tsconfig = getTsconfig(fixture.path);
442+
expect(tsconfig).not.toBeNull();
443+
444+
const testmatcher = createPathsMatcher(tsconfig!)!;
445+
const mismatcher = createPathsMatcher(tsconfig!, { fallback: false })!;
446+
447+
expect(mismatcher('@mismatch')).toStrictEqual([]);
448+
const resolvedAttempts = await getTscResolution('@test', fixture.path);
449+
expect(testmatcher('@test')).toStrictEqual([
450+
resolvedAttempts[0].filePath.slice(0, -3),
451+
]);
452+
453+
await fixture.rm();
454+
});
455+
430456
test('matches absolute paths', async () => {
431457
const fixture = await createFixture({
432458
'tsconfig.json': createTsconfigJson({

0 commit comments

Comments
 (0)