From f2173eea65e2f0835ba101058dfd6ee4e1167861 Mon Sep 17 00:00:00 2001 From: anchengjian Date: Wed, 11 Dec 2019 22:18:24 +0800 Subject: [PATCH] feat: Add support for alias with array of paths (#376) --- src/normalizeOptions.js | 8 +++++++- src/resolvePath.js | 12 ++++++++++++ test/index.test.js | 21 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/normalizeOptions.js b/src/normalizeOptions.js index 90f7a3f..30badba 100644 --- a/src/normalizeOptions.js +++ b/src/normalizeOptions.js @@ -90,7 +90,13 @@ function getAliasSubstitute(value, isKeyRegExp) { } if (!isKeyRegExp) { - return ([, match]) => `${value}${match}`; + return ([, match]) => { + // Alias with array of paths + if (Array.isArray(value)) { + return value.map(v => `${v}${match}`); + } + return `${value}${match}`; + }; } const parts = value.split('\\\\'); diff --git a/src/resolvePath.js b/src/resolvePath.js index 7778bf8..fcb3818 100644 --- a/src/resolvePath.js +++ b/src/resolvePath.js @@ -64,6 +64,18 @@ function resolvePathFromAliasConfig(sourcePath, currentFile, opts) { return null; } + // Alias with array of paths + if (Array.isArray(aliasedSourceFile)) { + return aliasedSourceFile + .map(asf => { + if (isRelativePath(asf)) { + return toLocalPath(toPosixPath(mapToRelative(opts.cwd, currentFile, asf))); + } + return asf; + }) + .find(src => nodeResolvePath(src, path.dirname(currentFile), opts.extensions)); + } + if (isRelativePath(aliasedSourceFile)) { return toLocalPath(toPosixPath( mapToRelative(opts.cwd, currentFile, aliasedSourceFile)), diff --git a/test/index.test.js b/test/index.test.js index c26e4ec..384f545 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1046,6 +1046,27 @@ describe('module-resolver', () => { ); }); + // fix: https://github.com/tleunen/babel-plugin-module-resolver/issues/261 + it('Alias with array of paths', () => { + testWithImport( + 'testArr/tools', + '../test/tools', + { + babelrc: false, + plugins: [ + [plugin, { + root: './src', + alias: { + testArr: ['./src', '/test', './test'], + }, + cwd: 'packagejson', + }], + ], + filename: './test/testproject/src/app.js', + }, + ); + }); + describe('unknown filename', () => { const unknownFileTransformerOpts = { babelrc: false,