UNPKG

bob-the-bundler

Version:
39 lines (38 loc) 1.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.rewriteCodeImports = void 0; const tslib_1 = require("tslib"); const fse = tslib_1.__importStar(require("fs-extra")); const path = tslib_1.__importStar(require("path")); function isFolderSync(path) { try { return fse.statSync(path).isDirectory(); } catch (e) { return false; } } function rewriteSourceValue(sourceValue, relativeDirname) { if (sourceValue.startsWith(".") && sourceValue.endsWith(".js") === false) { const targetPath = path.resolve(relativeDirname, sourceValue); // If the target path is a folder, we need to import from the index.js file if (isFolderSync(targetPath)) { sourceValue += "/index"; } sourceValue += ".js"; } return sourceValue; } /** * Rewrite import and export statements to append the correct .js file extension when needed */ function rewriteCodeImports(fileContents, absoluteFilePath) { const relativeDirname = path.dirname(absoluteFilePath); return fileContents.replace( /* this regex should hopefully catch all kind of import/export expressions that are relative. */ /((?:import|export)\s+[\s\w,{}*]*\s+from\s+["'])((?:\.\/|\.\.\/)(?:(?!\.js).)+)(["'])/g, (_, importFromPart, modulePath, hyphenEndPart) => { const sourcePath = rewriteSourceValue(modulePath, relativeDirname); return `${importFromPart}${sourcePath}${hyphenEndPart}`; }); } exports.rewriteCodeImports = rewriteCodeImports;