vite-plugin-serve-static

raw JSON →
2.2.0 verified Mon Apr 27 auth: no javascript

A Vite plugin (v2.2.0, stable, MIT) for serving arbitrary static files outside the standard `public` directory during local development. Unlike the built-in `publicDir` or `server.fs.allow`, this plugin supports regex-based URL-to-file mapping with flexible resolver functions, making it ideal for monorepos or projects where static files live in external directories. Requires Node >=20 and Vite >=5.0.0 <9.0.0. Note: does not handle production builds or serve.

error Error: Dynamic require of "vite-plugin-serve-static" is not supported
cause Using CommonJS require() with ESM-only package v2+.
fix
Switch to import statement or use dynamic import().
error ERR_PNPM_PEER_DEP_INSTALL_FAIL  Cannot install with --frozen-lockfile due to peer dependency mismatch on vite
cause Incompatible Vite version (e.g., <5.0.0 or >=9.0.0).
fix
Update Vite to >=5.0.0 <9.0.0 (latest Vite 7 is supported).
error [vite] http proxy error: /metadata.json: Error: ENOENT: no such file or directory
cause The resolve path is relative but Vite's working directory is not project root.
fix
Use absolute paths (e.g., path.resolve(__dirname, 'metadata.json')).
breaking Minimum Node.js version increased to 20.
fix Upgrade Node.js to 20 or later, or pin to v1.x.
breaking Vite peer dependency updated to >=5.0.0 <9.0.0.
fix Ensure Vite version is at least 5.0.0.
deprecated v1.x used CommonJS exports; v2 is ESM-only.
fix Migrate to ESM imports (no require()).
gotcha The plugin only applies during dev server, not in production builds.
fix Use separate static file serving in production (e.g., nginx, express).
gotcha Resolve paths must be absolute; relative paths can misbehave.
fix Use path.resolve or path.join with __dirname.
npm install vite-plugin-serve-static
yarn add vite-plugin-serve-static
pnpm add vite-plugin-serve-static

Configures serve-static plugin with two rules: static file via string path and dynamic file via resolver function.

import path from 'path';
import { defineConfig } from 'vite';
import serveStatic from 'vite-plugin-serve-static';

export default defineConfig({
  plugins: [
    serveStatic({
      rules: [
        {
          pattern: /^\/metadata\.json$/,
          resolve: path.resolve(__dirname, 'metadata.json'),
        },
        {
          pattern: /^\/photos\/(.*)/,
          resolve: (groups) => path.join(__dirname, '..', 'photos', groups[1]),
        },
      ],
      contentType: 'application/json',
    }),
  ],
});