Skip to content

Commit d03715d

Browse files
gpawliktleunen
authored andcommitted
feat: Ability to declare aliases in an array to preserve the order (#243)
1 parent 6cfad08 commit d03715d

3 files changed

Lines changed: 70 additions & 6 deletions

File tree

src/normalizeOptions.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,13 +97,21 @@ function normalizeAlias(optsAlias) {
9797
return [];
9898
}
9999

100-
const aliasKeys = Object.keys(optsAlias);
100+
const aliasArray = Array.isArray(optsAlias) ? optsAlias : [optsAlias];
101101

102-
return aliasKeys.map(key => (
103-
isRegExp(key) ?
104-
getAliasPair(key, optsAlias[key]) :
105-
getAliasPair(`^${key}(/.*|)$`, `${optsAlias[key]}\\1`)
106-
));
102+
return aliasArray.reduce((acc, alias) => {
103+
const aliasKeys = Object.keys(alias);
104+
105+
aliasKeys.forEach((key) => {
106+
const aliasPair = isRegExp(key)
107+
? getAliasPair(key, alias[key])
108+
: getAliasPair(`^${key}(/.*|)$`, `${alias[key]}\\1`);
109+
110+
acc.push(aliasPair);
111+
});
112+
113+
return acc;
114+
}, []);
107115
}
108116

109117
function normalizeTransformedFunctions(optsTransformFunctions) {

test/index.test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,43 @@ describe('module-resolver', () => {
634634
);
635635
});
636636
});
637+
638+
describe('correct alias order application', () => {
639+
const arrayAliasTransformerOpts = {
640+
babelrc: false,
641+
plugins: [
642+
[plugin, {
643+
alias: [{
644+
'~/foo': './src/lib/foo',
645+
}, {
646+
'~/bar': './src/lib/bar',
647+
}, {
648+
'~': './src',
649+
}],
650+
}],
651+
],
652+
};
653+
654+
it('should resolve aliases following the insertion order', () => {
655+
testWithImport(
656+
'~/foo',
657+
'./src/lib/foo',
658+
arrayAliasTransformerOpts,
659+
);
660+
661+
testWithImport(
662+
'~/bar',
663+
'./src/lib/bar',
664+
arrayAliasTransformerOpts,
665+
);
666+
667+
testWithImport(
668+
'~',
669+
'./src',
670+
arrayAliasTransformerOpts,
671+
);
672+
});
673+
});
637674
});
638675

639676
describe('with custom cwd', () => {

test/normalizeOptions.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,23 @@ describe('normalizeOptions', () => {
3333
expect(result).not.toBe(result2);
3434
expect(normalizeOptions.recomputations()).toEqual(2);
3535
});
36+
37+
it('should correctly normalize alias option if it is an array', () => {
38+
const options = {
39+
alias: [
40+
{
41+
foo: 'A',
42+
bar: 'B',
43+
},
44+
{
45+
baz: 'C',
46+
},
47+
],
48+
};
49+
const { alias } = normalizeOptions('path/to/file.js', options);
50+
51+
expect(alias[0][0]).toEqual(/^foo(\/.*|)$/);
52+
expect(alias[1][0]).toEqual(/^bar(\/.*|)$/);
53+
expect(alias[2][0]).toEqual(/^baz(\/.*|)$/);
54+
});
3655
});

0 commit comments

Comments
 (0)