diff --git a/index.ts b/index.ts index 6ea0890..7e47118 100644 --- a/index.ts +++ b/index.ts @@ -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) { @@ -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`. diff --git a/test/index.js b/test/index.js index cbd04d7..95f7c86 100644 --- a/test/index.js +++ b/test/index.js @@ -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')); diff --git a/test/tsconfig.json b/test/tsconfig.json index 996e351..6cde3d9 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -7,7 +7,8 @@ "@foobar-react": ["foo/bar-react"], "@bar/*": ["bar/*"], "bar/*": ["bar/*"], - "@js": ["js"] + "@js": ["js"], + "$/*": ["*"] } } }