Created
August 25, 2025 20:49
-
-
Save Oluwasetemi/a254deb5126230c13e8bc8fd8d86ca3b to your computer and use it in GitHub Desktop.
Sample vite plugin for asset management
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { Plugin } from "vite"; | |
import fs from "node:fs"; | |
import path from "node:path"; | |
export function contentAssetsPlugin(): Plugin { | |
return { | |
name: "content-assets", | |
configureServer(server) { | |
// Serve images from content directory | |
server.middlewares.use("/content-assets", (req, res, next) => { | |
if (!req.url) | |
return next(); | |
const filePath = path.join(process.cwd(), "src/content", req.url); | |
if (fs.existsSync(filePath)) { | |
const ext = path.extname(filePath); | |
const mimeTypes: Record<string, string> = { | |
".jpg": "image/jpeg", | |
".jpeg": "image/jpeg", | |
".png": "image/png", | |
".gif": "image/gif", | |
".webp": "image/webp", | |
}; | |
res.setHeader("Content-Type", mimeTypes[ext] || "application/octet-stream"); | |
fs.createReadStream(filePath).pipe(res); | |
} | |
else { | |
next(); | |
} | |
}); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment