diff --git a/src/normalizeOptions.js b/src/normalizeOptions.js index 90da1ba..5a2ea42 100644 --- a/src/normalizeOptions.js +++ b/src/normalizeOptions.js @@ -97,13 +97,21 @@ function normalizeAlias(optsAlias) { return []; } - const aliasKeys = Object.keys(optsAlias); + const aliasArray = Array.isArray(optsAlias) ? optsAlias : [optsAlias]; - return aliasKeys.map(key => ( - isRegExp(key) ? - getAliasPair(key, optsAlias[key]) : - getAliasPair(`^${key}(/.*|)$`, `${optsAlias[key]}\\1`) - )); + return aliasArray.reduce((acc, alias) => { + const aliasKeys = Object.keys(alias); + + aliasKeys.forEach((key) => { + const aliasPair = isRegExp(key) + ? getAliasPair(key, alias[key]) + : getAliasPair(`^${key}(/.*|)$`, `${alias[key]}\\1`); + + acc.push(aliasPair); + }); + + return acc; + }, []); } function normalizeTransformedFunctions(optsTransformFunctions) { diff --git a/test/index.test.js b/test/index.test.js index 65b0198..1b2ff34 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -634,6 +634,43 @@ describe('module-resolver', () => { ); }); }); + + describe('correct alias order application', () => { + const arrayAliasTransformerOpts = { + babelrc: false, + plugins: [ + [plugin, { + alias: [{ + '~/foo': './src/lib/foo', + }, { + '~/bar': './src/lib/bar', + }, { + '~': './src', + }], + }], + ], + }; + + it('should resolve aliases following the insertion order', () => { + testWithImport( + '~/foo', + './src/lib/foo', + arrayAliasTransformerOpts, + ); + + testWithImport( + '~/bar', + './src/lib/bar', + arrayAliasTransformerOpts, + ); + + testWithImport( + '~', + './src', + arrayAliasTransformerOpts, + ); + }); + }); }); describe('with custom cwd', () => { diff --git a/test/normalizeOptions.test.js b/test/normalizeOptions.test.js index f712c53..91e9e69 100644 --- a/test/normalizeOptions.test.js +++ b/test/normalizeOptions.test.js @@ -33,4 +33,23 @@ describe('normalizeOptions', () => { expect(result).not.toBe(result2); expect(normalizeOptions.recomputations()).toEqual(2); }); + + it('should correctly normalize alias option if it is an array', () => { + const options = { + alias: [ + { + foo: 'A', + bar: 'B', + }, + { + baz: 'C', + }, + ], + }; + const { alias } = normalizeOptions('path/to/file.js', options); + + expect(alias[0][0]).toEqual(/^foo(\/.*|)$/); + expect(alias[1][0]).toEqual(/^bar(\/.*|)$/); + expect(alias[2][0]).toEqual(/^baz(\/.*|)$/); + }); });