From 70f132664f102a9dc09e1c1f6f9ebcfe0ad860f7 Mon Sep 17 00:00:00 2001 From: ccloli <8115912+ccloli@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:28:39 +0800 Subject: [PATCH] feat: improve alias replacement to handle relative path correctly Now it should handle something like `"@": "./src"` correctly, and not mess it up with regular npm package that has a `@` prefix. --- .../babel/replace-import-path-aliases.ts | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/app/src/sandbox/eval/transpilers/babel/replace-import-path-aliases.ts b/packages/app/src/sandbox/eval/transpilers/babel/replace-import-path-aliases.ts index c49fc15a010..34d3d594f68 100644 --- a/packages/app/src/sandbox/eval/transpilers/babel/replace-import-path-aliases.ts +++ b/packages/app/src/sandbox/eval/transpilers/babel/replace-import-path-aliases.ts @@ -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; - \ No newline at end of file