X Tutup
Skip to content

typeparameter/vite-plugin-serve-static

Repository files navigation

vite-plugin-serve-static

npm vite license: MIT

A simple Vite plugin for serving arbitrary static files that aren't in your public directory.

// vite.config.ts
import path from "path";

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

const serveStaticPlugin = serveStatic({
  rules: [
    {
      pattern: /^\/metadata\.json/,
      resolve: path.join(".", "metadata.json"),
    },
    {
      pattern: /^\/dog-photos\/.*/,
      resolve: ([match]) => path.join("..", "dog-photos", match),
    },
    {
      pattern: /^\/author-photos\/(.*)/,
      resolve: (groups) => path.join("..", "authors", groups[1]) + ".jpg",
    },
  ],
});

export default defineConfig({
  plugins: [serveStaticPlugin],
});

Config

The configuration is provided as an object with rules, plus an optional global contentType.

Each rule defines which patterns to intercept and how to resolve them. Each pattern is defined as a regular expression. The resolve property can either be a string containing the path to a single file or a function that returns a string given the result of executing the pattern against the request path. Rules can also specify headers to apply per match.

const serveStaticPlugin = serveStatic({
  contentType: "text/plain",
  rules: [
    {
      pattern: /^\/metadata\.json/,
      resolve: path.join(".", "metadata.json"),
      headers: {
        "Cache-Control": "no-store",
        "X-Static-File": "true",
      },
    },
  ],
});

License

Licensed under the MIT License.

About

📄 Serve static files during local development

Topics

Resources

License

Stars

Watchers

Forks

Contributors

X Tutup