Skip to content

Commit

Permalink
feat: improve alias replacement to handle relative path correctly
Browse files Browse the repository at this point in the history
Now it should handle something like `"@": "./src"` correctly, and
not mess it up with regular npm package that has a `@` prefix.
  • Loading branch information
ccloli committed Sep 15, 2023
1 parent 53f293c commit 70f1326
Showing 1 changed file with 21 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,28 @@
* Replaces alias in the esmodule code
*/
const createRegex = (pathMap: any) => {
const mapKeysStr = Object.keys(pathMap).map(item => item.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')).reduce((acc, cur) => `${acc}|${cur}`);
const regexStr = `^(import[\\s\\S]*?from?\\s+["|'])(${mapKeysStr})(.*)(["|'];?)$`;
return new RegExp(regexStr, "gm");
}

const mapKeysStr = Object.keys(pathMap)
.map(item => item.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'))
.reduce((acc, cur) => `${acc}|${cur}`);
const regexStr = `^(import[\\s\\S]*?from?\\s+["|'])(${mapKeysStr})((?=\\/).*|)(["|'];?)$`;
return new RegExp(regexStr, 'gm');
};

const replaceImportPathAliases = (code: string, pathMap: any) => {
const regex = createRegex(pathMap);
const replacer = (_: string, g1: string, aliasGrp: string, restPathGrp: string, g4: string) => `${g1}${pathMap[aliasGrp]}${restPathGrp}${g4}`;
const replacer = (
_: string,
g1: string,
aliasGrp: string,
restPathGrp: string,
g4: string
) =>
`${g1}${
// if the alias is a relative path, then it's related to the root directory,
// so ./ is equivalent to /
pathMap[aliasGrp] ? pathMap[aliasGrp].replace(/^\.\//, '/') : aliasGrp
}${restPathGrp}${g4}`;
return code.replace(regex, replacer);
}
};

export default replaceImportPathAliases;

0 comments on commit 70f1326

Please sign in to comment.