Skip to content

Commit

Permalink
feat: add fallback option to avoid meaningless result.
Browse files Browse the repository at this point in the history
  • Loading branch information
emosheeep committed Jan 12, 2024
1 parent 33d4f81 commit 3e42d9d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/paths-matcher/index.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -40,6 +40,7 @@ const parsePaths = (
*/
export const createPathsMatcher = (
tsconfig: TsConfigResult,
{ fallback = true }: MatchOptions = {},
) => {
if (!tsconfig.config.compilerOptions) {
return null;
Expand Down Expand Up @@ -97,7 +98,7 @@ export const createPathsMatcher = (

if (!matchedValue) {
return (
baseUrl
(baseUrl && fallback)
? [slash(path.join(resolvedBaseUrl, specifier))]
: []
);
Expand Down
9 changes: 9 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
26 changes: 26 additions & 0 deletions tests/specs/create-paths-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,32 @@ export default testSuite(({ describe }) => {
await fixture.rm();
});

test('fallback option', async () => {
const fixture = await createFixture({
'tsconfig.json': createTsconfigJson({
compilerOptions: {
paths: {
'@test': ['./test'],
},
},
}),
});

const tsconfig = getTsconfig(fixture.path);
expect(tsconfig).not.toBeNull();

const testmatcher = createPathsMatcher(tsconfig!)!;
const mismatcher = createPathsMatcher(tsconfig!, { fallback: false })!;

expect(mismatcher('@mismatch')).toStrictEqual([]);
const resolvedAttempts = await getTscResolution('@test', fixture.path);
expect(testmatcher('@test')).toStrictEqual([
resolvedAttempts[0].filePath.slice(0, -3),
]);

await fixture.rm();
});

test('matches absolute paths', async () => {
const fixture = await createFixture({
'tsconfig.json': createTsconfigJson({
Expand Down

0 comments on commit 3e42d9d

Please sign in to comment.