-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvite-plugin-remove-html.mjs
More file actions
59 lines (52 loc) · 1.83 KB
/
vite-plugin-remove-html.mjs
File metadata and controls
59 lines (52 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { readFile, writeFile, readdir } from "fs/promises";
import { join } from "path";
/**
* Astro integration to remove .html extensions from links
*/
export function removeHtmlExtension() {
return {
name: "remove-html-extension",
hooks: {
"astro:build:done": async ({ dir }) => {
console.log("Removing .html extensions from links...");
const htmlFiles = [];
async function findHtmlFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(directory, entry.name);
if (entry.isDirectory()) {
await findHtmlFiles(fullPath);
} else if (entry.name.endsWith(".html")) {
htmlFiles.push(fullPath);
}
}
}
await findHtmlFiles(dir.pathname);
console.log(`Found ${htmlFiles.length} HTML files to process`);
let processedCount = 0;
for (const filePath of htmlFiles) {
try {
let content = await readFile(filePath, "utf-8");
const before = content.length;
// Remove .html from href, value, and content attributes
// This handles links, canonical URLs, og:url meta tags, etc.
content = content.replace(
/(href|value|content)=(["'])([^"']*?)\.html\2/g,
"$1=$2$3$2",
);
const after = content.length;
if (before !== after) {
await writeFile(filePath, content, "utf-8");
processedCount++;
}
} catch (err) {
console.warn(`Could not process ${filePath}:`, err.message);
}
}
console.log(
`✓ Processed ${processedCount} files, removed .html extensions`,
);
},
},
};
}