From 4c566845598a2129f8cf70b81f14fd7835f95111 Mon Sep 17 00:00:00 2001 From: Telokis Date: Thu, 23 Aug 2018 23:41:42 +0200 Subject: [PATCH] fix: Escape key of alias to support using $ prefix (#313) Closes #312 (See #312 for detailed explanation) --- src/normalizeOptions.js | 3 ++- src/utils.js | 4 ++++ test/index.test.js | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/normalizeOptions.js b/src/normalizeOptions.js index 5eff27e..56736b3 100644 --- a/src/normalizeOptions.js +++ b/src/normalizeOptions.js @@ -6,6 +6,7 @@ import findBabelConfig from 'find-babel-config'; import glob from 'glob'; import pkgUp from 'pkg-up'; +import { escapeRegExp } from './utils'; import defaultResolvePath from './resolvePath'; @@ -79,7 +80,7 @@ function normalizeRoot(optsRoot, cwd) { } function getAliasTarget(key, isKeyRegExp) { - const regExpPattern = isKeyRegExp ? key : `^${key}(/.*|)$`; + const regExpPattern = isKeyRegExp ? key : `^${escapeRegExp(key)}(/.*|)$`; return new RegExp(regExpPattern); } diff --git a/src/utils.js b/src/utils.js index 062cf1c..42b107e 100644 --- a/src/utils.js +++ b/src/utils.js @@ -80,3 +80,7 @@ export function mapPathString(nodePath, state) { export function isImportCall(types, calleePath) { return types.isImport(calleePath.node.callee); } + +export function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/test/index.test.js b/test/index.test.js index 8d4f683..2ee261f 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -342,6 +342,7 @@ describe('module-resolver', () => { '^regexp-priority': './hit', 'regexp-priority$': './miss', 'regexp-priority': './miss', + '$src': './test/testproject/src/' }, }], ], @@ -466,6 +467,15 @@ describe('module-resolver', () => { ); }); + it('should escape regexp', () => { + // See https://github.com/tleunen/babel-plugin-module-resolver/issues/312 + testWithImport( + '$src/app', + './test/testproject/src/app', + aliasTransformerOpts, + ); + }) + describe('with a regular expression', () => { it('should support replacing parts of a path', () => { testWithImport(