babel-plugin-sfcc-modules
Version:
Babel plugin to handle non-standard module paths used by Salesforce Commerce Cloud (SFCC)
52 lines (51 loc) • 2.56 kB
JavaScript
import t from "@babel/types";
import importsVisitor from "imports-visitor";
import fs from "node:fs";
import path from "node:path";
//#region src/index.ts
const SUPPORTED_EXTENSIONS = [
"js",
"ds",
"json"
];
const getModulePath = (moduleName, basePath, cartridge, target) => {
const relativePath = path.relative(path.dirname(moduleName), `${basePath}/${cartridge}${target}`);
return (relativePath.includes(".") ? "" : "./") + relativePath;
};
const plugin = (_babel, { cartridgePath, basePath }) => ({ visitor: {
Program(thePath, state) {
const imports = [];
thePath.traverse(importsVisitor, { imports });
for (const imp of imports) {
/**
* Finds and sets the rewrittten module path.
*
* @param findCartridge a function to find the cartridge
*/
const resolve = (findCartridge) => {
const target = imp.source.slice(1);
const foundCartridge = findCartridge(target);
if (foundCartridge) imp.source = getModulePath(state.file.opts.filename, basePath, foundCartridge, target);
};
if (imp.source.indexOf("*/") === 0) resolve((target) => cartridgePath.find((cartridge) => SUPPORTED_EXTENSIONS.find((extension) => fs.existsSync(`${basePath}/${cartridge}${target}.${extension}`))));
if (imp.source.indexOf("~/") === 0) resolve(() => path.relative(basePath, path.dirname(state.file.opts.filename)).split(path.sep)[0]);
}
},
MemberExpression(thePath, state) {
if (thePath.node.object.type === "Identifier" && thePath.node.object.name === "module" && thePath.node.property.name === "superModule") {
const pathToModule = path.relative(basePath, state.file.opts.filename);
const shortenedPathParts = pathToModule.split(path.sep).slice(1);
const lastPart = shortenedPathParts.at(-1);
if (!lastPart) return;
shortenedPathParts[shortenedPathParts.length - 1] = lastPart.replace(/\.[^.]+$/, "");
const shortenedPathToModule = `/${shortenedPathParts.join(path.sep)}`;
const cartridge = pathToModule.split(path.sep)[0];
const foundCartridge = cartridgePath.slice(cartridgePath.indexOf(cartridge) + 1).find((theCartridge) => SUPPORTED_EXTENSIONS.find((extension) => fs.existsSync(`${basePath}/${theCartridge}${shortenedPathToModule}.${extension}`)));
let foundRequire;
if (foundCartridge) foundRequire = getModulePath(state.file.opts.filename, basePath, foundCartridge, shortenedPathToModule);
thePath.replaceWith(foundRequire ? t.callExpression(t.identifier("require"), [t.stringLiteral(foundRequire)]) : t.identifier("undefined"));
}
}
} });
//#endregion
export { plugin as default };