Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow wildcards for matching except names #4

Merged
merged 1 commit into from
May 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions __specs__/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,45 @@ describe('Should create a correct regular expression for excluding node_modules'
});
});

describe('Should be able to convert wildcards in parameters to matching pattern in the regular expression', () => {
/**
* @type {TestCase[]}
*/
const testCases = [
{
description: 'Wildcard occurs in the only argument',
params: ['react-*'],
expected: X
? /node_modules\\(?!(react\-(?:.*))\\)/i
: /node_modules\/(?!(react\-(?:.*))\/)/i
},
{
description: 'Wildcard occurs in the second argument out of three',
params: ['abc', 'mno*', 'xvz'],
expected: X
? /node_modules\\(?!(abc|mno(?:.*)|xvz)\\)/i
: /node_modules\/(?!(abc|mno(?:.*)|xvz)\/)/i
},
{
description: 'Wildcard used for scoped packages',
params: ['@awesomecorp/*'],
expected: X
? /node_modules\\(?!(@awesomecorp\\(?:.*))\\)/i
: /node_modules\/(?!(@awesomecorp\/(?:.*))\/)/i
}
];

testCases.forEach(function ({ params, expected, description }, i) {
test(`Test case #${i + 1}: ${description}`, function () {
const result = babelLoaderExcludeNodeModulesExcept(params);
expect(result).toEqual(expected);
});
});
});

/**
* @typedef {Object} TestCase
* @property {string[]} params
* @property {RegExp} expected
* @property {string} [description]
*/
24 changes: 23 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,29 @@ function babelLoaderExcludeNodeModulesExcept(exceptionList) {
});

const alternationGroup =
'(' + normalizedExceptionList.map(escapeStringRegexp).join('|') + ')';
'(' +
normalizedExceptionList
.map((item) => {
// Breaking down string by wildcards. For every
// occurrance between wildcards build the portion
// with escapeStringRegexp.
// For the wildcards, replace them by a non-capturing
// group matching everything.
const match = item.match(/([^*]*)/g);
return match
.map((m, i) => {
if (m.length > 0) {
return escapeStringRegexp(m);
} else if (i !== match.length - 1 && m.length === 0) {
return '(?:.*)';
} else {
return '';
}
})
.join('');
})
.join('|') +
')';

// If the exception list includes e.g. "react", we don't want to
// accidentally make an exception for "react-dom", so make sure to
Expand Down