Skip to content

Support server entry — $ vite path/to/server.js / vite.config.js#server. #6394

@brillout

Description

@brillout

Clear and concise description of the problem

Vite does not support server entries.

For example, the playground/ssr-vue/server.js file is not processed by Vite which means:

  • The user cannot use Vite constants such as import.meta.env.
  • The user cannot use TypeScript (without using an extra tool such as ts-node).
  • If the user makes a change to server.js then the user has to manually stop and re-start the server.

Suggested solution

We add an argument to the CLI command vite.

$ vite ./server.js

The argument is optional and if omitted Vite behaves as it does today (it starts Vite's built-in dev server).

// server.js

import express from 'express'
import vite from 'vite'

startServer()

async function startServer() {
  const app = express()

  const { middlewares: viteMiddleware } = await vite.createServer({
    server: { middlewareMode: 'ssr' },
  })
  app.use(viteMiddleware)

  app.listen(process.env.PORT || 3000)
  console.log(`Server running at http://localhost:${port}`)
}

The whole vite.loadSSRModule dance would be taken care of.

We can even consider adding support for HMR and, if HMR is not applicable, to automatically reload the server by killing process.env.PORT with e.g. kill-port. (It's a common convention to use process.env.PORT as server port.)

The user can also define the server entry with vite.config.js#server.

// vite.config.js
export default {
  server: 'server.js'
}
# No need to specify the server entry here
$ vite

Alternative

No response

Additional context

This ticket is part of Vite Server RFC.

Validations

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions