Skip to content

Commit

Permalink
feat: Allow using matches from externals for regex matching (#825)
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Dec 2, 2021
1 parent ff2165b commit 905222e
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 6 deletions.
25 changes: 22 additions & 3 deletions src/index.js
Expand Up @@ -160,6 +160,7 @@ function ncc (
const externalMap = (() => {
const regexps = [];
const aliasMap = new Map();
const regexCache = new Map();

function set(key, value) {
if (key instanceof RegExp)
Expand All @@ -169,9 +170,27 @@ function ncc (

function get(key) {
if (aliasMap.has(key)) return aliasMap.get(key);

const matchedRegex = regexps.find(regex => regex.test(key));
return matchedRegex !== null ? aliasMap.get(matchedRegex) : null;
if (regexCache.has(key)) return regexCache.get(key);

for (const regex of regexps) {
const matches = key.match(regex)

if (matches) {
let result = aliasMap.get(regex)

if (matches.length > 1) {
// allow using match from regex in result
// e.g. caniuse-lite(/.*) -> caniuse-lite$1
result = result.replace(/(\$\d)/g, (match) => {
const index = parseInt(match.substr(1), 10)
return matches[index] || match
})
}
regexCache.set(key, result)
return result
}
}
return null;
}

return { get, set };
Expand Down
2 changes: 1 addition & 1 deletion test/unit.test.js
Expand Up @@ -44,6 +44,7 @@ for (const unitTest of fs.readdirSync(`${__dirname}/unit`)) {
'piscina': 'piscina',
'externaltest': 'externalmapped',
'/\\w+-regex/': 'regexexternal',
'/external-replace(/.*)/': 'external-replace/replaced$1'
}
}, opts)).then(
async ({ code, assets, map }) => {
Expand Down Expand Up @@ -88,4 +89,3 @@ for (const unitTest of fs.readdirSync(`${__dirname}/unit`)) {
)
});
}

3 changes: 2 additions & 1 deletion test/unit/externals/input.js
@@ -1,6 +1,7 @@
const external = require('externaltest');
const regexpExternal = require('external-regex');
const regexpExternalMatch = require('external-replace/some-file')

console.log(external);
console.log(regexpExternal);

console.log(regexpExternalMatch);
11 changes: 10 additions & 1 deletion test/unit/externals/output.js
@@ -1,6 +1,14 @@
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({

/***/ 378:
/***/ ((module) => {

"use strict";
module.exports = require("external-replace/replaced/some-file");

/***/ }),

/***/ 830:
/***/ ((module) => {

Expand Down Expand Up @@ -60,10 +68,11 @@ var __webpack_exports__ = {};
(() => {
const external = __nccwpck_require__(830);
const regexpExternal = __nccwpck_require__(958);
const regexpExternalMatch = __nccwpck_require__(378)

console.log(external);
console.log(regexpExternal);

console.log(regexpExternalMatch);

})();

Expand Down

0 comments on commit 905222e

Please sign in to comment.