Skip to content

Commit

Permalink
fix: remove the directories if they are empty
Browse files Browse the repository at this point in the history
  • Loading branch information
SeanCassiere committed Sep 7, 2024
1 parent 3a4ad77 commit b6ab87f
Showing 1 changed file with 40 additions and 12 deletions.
52 changes: 40 additions & 12 deletions packages/vinxi/lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { mkdir, rm } from "fs/promises";
import { createRequire } from "module";
import { build, copyPublicAssets, createNitro, prerender } from "nitropack";

import { readdirSync, writeFileSync } from "node:fs";
import { existsSync, readdirSync, writeFileSync } from "node:fs";
import { pathToFileURL } from "node:url";

import { H3Event, createApp } from "../runtime/server.js";
Expand Down Expand Up @@ -322,24 +322,32 @@ export async function createBuild(app, buildConfig) {
for (const router of app.config.routers.filter(
(r) => r.type === "http" && r.target === "server",
)) {
const assetsDir = join(
nitro.options.output.publicDir,
router.base,
"assets",
);
const routerDir = join(nitro.options.output.publicDir, router.base);
const assetsDir = join(routerDir, "assets");
if (!existsSync(assetsDir)) {
continue;
}
const files = readdirSync(assetsDir);
for (const file of files) {

let hasFilesDeleted = false;
const assetFiles = readdirSync(assetsDir);
for (const assetName of assetFiles) {
if (
file.endsWith(".js") ||
file.endsWith(".mjs") ||
file.endsWith(".cjs")
assetName.endsWith(".js") ||
assetName.endsWith(".mjs") ||
assetName.endsWith(".cjs")
) {
await rm(join(assetsDir, file));
if (!hasFilesDeleted) {
hasFilesDeleted = true;
}
await rm(join(assetsDir, assetName));
}
}

// if the router dir is empty (including its subdirectories), remove it
// if the subdirectories are empty, they will be removed recursively
if (hasFilesDeleted) {
await deleteEmptyDirs(routerDir);
}
}

await app.hooks.callHook("app:build:nitro:assets:copy:end", { app, nitro });
Expand Down Expand Up @@ -792,3 +800,23 @@ function browserBuild() {
},
};
}

/**
* Recursively deletes empty directories starting from the given directory
*
* @param {string} dir
* @returns void
*/
async function deleteEmptyDirs(dir) {
const files = readdirSync(dir);
if (files.length === 0) {
await rm(dir);
return;
}
for (const file of files) {
const filePath = join(dir, file);
if (existsSync(filePath) && !file.startsWith(".")) {
deleteEmptyDirs(filePath);
}
}
}

0 comments on commit b6ab87f

Please sign in to comment.