Vite - Before the Server Starts

04/14/2022, Thu
Categories: #Tooling #javascript
Tags: #frontend

Use the 'configure-server'

Create a Vite application from the new project command with a template option. This command will create a simple TypeScript project.

npm create vite@latest a-vite-test -- --template vanilla-ts

While the Vite specific hook, configureServer, is intended for configuring the Vite dev server middleware, it also allows for early stage task configuration that might run on the command line prior to the Vite dev server starts up.

It is useful because it can also replicate the behavior of a 'before' callback.

import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    (() => ({
      name: 'configure-server',
      configureServer() {
        console.log('Do something early before the dev server starts up.');

        server.middlewares.use((req, res, next) => {
          // custom handle request...
        })
      }
    }))()
  ]
})