blog/lib/assets.ts

23 lines
766 B
TypeScript
Raw Normal View History

2024-06-24 17:31:11 +00:00
import { globSync } from "glob";
import { readFileSync } from "node:fs";
import { env } from "node:process";
import { join } from "node:path";
export const assetMap: Map<string, string> = new Map();
export function reloadAssets() {
assetMap.clear();
globSync("dist/_assets/*.manifest")
.map(
2024-06-27 04:22:58 +00:00
(manifest) => JSON.parse(readFileSync(manifest).toString()) as { [orig: string]: string },
2024-06-24 17:31:11 +00:00
)
2024-06-27 04:22:58 +00:00
.forEach((mapping) => Object.entries(mapping).forEach(([orig, hashed]) => assetMap.set(orig, hashed)));
2024-06-24 17:31:11 +00:00
}
export function asset(path: string): string {
2024-06-27 04:22:58 +00:00
const realPath = assetMap.has(path) ? assetMap.get(path)! : path;
2024-06-24 17:31:11 +00:00
2024-06-27 04:22:58 +00:00
return env.ASSETS_HOSTS ? new URL(realPath, env.ASSETS_HOSTS).toString() : join("/_assets/", realPath);
2024-06-24 17:31:11 +00:00
}