wxt
Version:
⚡ Next-gen Web Extension Framework
60 lines (59 loc) • 1.92 kB
JavaScript
import { dirname, extname, resolve, join } from "node:path";
import { getEntrypointBundlePath } from "../../../utils/entrypoints.mjs";
import fs, { ensureDir } from "fs-extra";
import { normalizePath } from "../../../utils/paths.mjs";
export function multipageMove(entrypoints, config) {
return {
name: "wxt:multipage-move",
async writeBundle(_, bundle) {
for (const oldBundlePath in bundle) {
const entrypoint = entrypoints.find(
(entry) => !!normalizePath(entry.inputPath).endsWith(oldBundlePath)
);
if (entrypoint == null) {
config.logger.debug(
`No entrypoint found for ${oldBundlePath}, leaving in chunks directory`
);
continue;
}
const newBundlePath = getEntrypointBundlePath(
entrypoint,
config.outDir,
extname(oldBundlePath)
);
if (newBundlePath === oldBundlePath) {
config.logger.debug(
"HTML file is already in the correct location",
oldBundlePath
);
continue;
}
const oldAbsPath = resolve(config.outDir, oldBundlePath);
const newAbsPath = resolve(config.outDir, newBundlePath);
await ensureDir(dirname(newAbsPath));
await fs.move(oldAbsPath, newAbsPath, { overwrite: true });
const renamedChunk = {
...bundle[oldBundlePath],
fileName: newBundlePath
};
delete bundle[oldBundlePath];
bundle[newBundlePath] = renamedChunk;
}
removeEmptyDirs(config.outDir);
}
};
}
export async function removeEmptyDirs(dir) {
const files = await fs.readdir(dir);
for (const file of files) {
const filePath = join(dir, file);
const stats = await fs.stat(filePath);
if (stats.isDirectory()) {
await removeEmptyDirs(filePath);
}
}
try {
await fs.rmdir(dir);
} catch {
}
}