@plugjs/plug
Version:
PlugJS Build System ===================
55 lines (54 loc) • 2.51 kB
JavaScript
// plugs/esbuild/fix-extensions.ts
import path from "node:path";
import { stat } from "../../fs.mjs";
import { assertAbsolutePath, resolveAbsolutePath, resolveFile } from "../../paths.mjs";
function fixExtensions() {
return {
name: "fix-extensions",
setup(build) {
build.initialOptions.bundle = true;
const cjs = build.initialOptions.outExtension?.[".cjs"] || ".cjs";
const mjs = build.initialOptions.outExtension?.[".mjs"] || ".mjs";
const js = build.initialOptions.outExtension?.[".js"] || ".js";
const exts = build.initialOptions.resolveExtensions || [".ts", ".js", ".tsx", ".jsx"];
build.onResolve({ filter: /.*/ }, async (args) => {
if (!args.importer) return null;
if (!args.path.match(/^\.\.?\//)) return { external: true };
const resolveDir = args.resolveDir;
assertAbsolutePath(resolveDir);
const resolved = resolveAbsolutePath(resolveDir, args.path);
if (resolveFile(resolved)) return { path: args.path, external: true };
const match = args.path.match(/(.*)(\.[mc]?js$)/);
if (match) {
const [, name, ext] = match;
const tspath = name + ext.replace("js", "ts");
const tsfile = resolveAbsolutePath(resolveDir, tspath);
if (resolveFile(tsfile)) {
const newext = ext === ".mjs" ? mjs : ext === ".cjs" ? cjs : js;
return { path: name + newext, external: true };
}
}
for (const ext of exts) {
const fileName = `${args.path}${ext}`;
const filePath = path.resolve(args.resolveDir, fileName);
const isFile = await stat(filePath).then((stat2) => stat2.isFile(), (error) => void error);
if (isFile) return { path: `${args.path}${js}`, external: true };
}
const dirPath = path.resolve(args.resolveDir, args.path);
const isDir = await stat(dirPath).then((stat2) => stat2.isDirectory(), (error) => void error);
if (!isDir) return { external: true };
for (const ext of exts) {
const fileName = path.join(args.path, `index${ext}`);
const filePath = path.resolve(args.resolveDir, fileName);
const isFile = await stat(filePath).then((stat2) => stat2.isFile(), (error) => void error);
if (isFile) return { path: `${args.path}/index${js}`, external: true };
}
return { external: true };
});
}
};
}
export {
fixExtensions
};
//# sourceMappingURL=fix-extensions.mjs.map