Skip to content

Commit c65e138

Browse files
authored
feat: escape $ and ^ characters from path (simonhaenisch#17)
1 parent da50ce4 commit c65e138

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

index.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ export const typescriptPaths = ({
3535
const hasMatchingPath =
3636
!!compilerOptions.paths &&
3737
Object.keys(compilerOptions.paths).some((path) =>
38-
new RegExp('^' + path.replace('*', '.+') + '$').test(importee),
38+
new RegExp('^' + escapeRegex(path.replace('*', '.+')) + '$').test(
39+
importee,
40+
),
3941
);
4042

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

102+
/**
103+
* Escapes $ and ^ characters in the given string. This is necessary if you
104+
* want to use `$/*` in your paths, for example.
105+
*/
106+
const escapeRegex = (str: string) => {
107+
return str.replace(/[$^]/g, '\\$&');
108+
};
109+
100110
export interface Options {
101111
/**
102112
* Whether to resolve to absolute paths; defaults to `true`.

test/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ try {
5656
join(__dirname, 'bar', 'foo.js'),
5757
);
5858

59+
// resolves $/* paths
60+
strictEqual(
61+
plugin.resolveId('$/foo/bar', ''),
62+
join(__dirname, 'foo', 'bar.js'),
63+
);
64+
5965
// resolves from a directory with index file
6066
strictEqual(plugin.resolveId('@js', ''), join(__dirname, 'js', 'index.js'));
6167

test/tsconfig.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
"@foobar-react": ["foo/bar-react"],
88
"@bar/*": ["bar/*"],
99
"bar/*": ["bar/*"],
10-
"@js": ["js"]
10+
"@js": ["js"],
11+
"$/*": ["*"]
1112
}
1213
}
1314
}

0 commit comments

Comments
 (0)