Skip to content

Commit

Permalink
feat: Ability to declare aliases in an array to preserve the order (#243
Browse files Browse the repository at this point in the history
)
  • Loading branch information
gpawlik authored and tleunen committed Dec 9, 2017
1 parent 6cfad08 commit d03715d
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/normalizeOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
37 changes: 37 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
19 changes: 19 additions & 0 deletions test/normalizeOptions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(\/.*|)$/);
});
});

0 comments on commit d03715d

Please sign in to comment.