Skip to content

feat: escape $ and ^ characters from path #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ export const typescriptPaths = ({
const hasMatchingPath =
!!compilerOptions.paths &&
Object.keys(compilerOptions.paths).some((path) =>
new RegExp('^' + path.replace('*', '.+') + '$').test(importee),
new RegExp('^' + escapeRegex(path.replace('*', '.+')) + '$').test(
importee,
),
);

if (!hasMatchingPath && !nonRelative) {
Expand Down Expand Up @@ -97,6 +99,14 @@ const getTsConfig = (configPath?: string): TsConfig => {
return { ...defaults, ...config };
};

/**
* Escapes $ and ^ characters in the given string. This is necessary if you
* want to use `$/*` in your paths, for example.
*/
const escapeRegex = (str: string) => {
return str.replace(/[$^]/g, '\\$&');
};

export interface Options {
/**
* Whether to resolve to absolute paths; defaults to `true`.
Expand Down
6 changes: 6 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ try {
join(__dirname, 'bar', 'foo.js'),
);

// resolves $/* paths
strictEqual(
plugin.resolveId('$/foo/bar', ''),
join(__dirname, 'foo', 'bar.js'),
);

// resolves from a directory with index file
strictEqual(plugin.resolveId('@js', ''), join(__dirname, 'js', 'index.js'));

Expand Down
3 changes: 2 additions & 1 deletion test/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"@foobar-react": ["foo/bar-react"],
"@bar/*": ["bar/*"],
"bar/*": ["bar/*"],
"@js": ["js"]
"@js": ["js"],
"$/*": ["*"]
}
}
}