vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
67.08k stars 6.02k forks source link

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

Open brillout opened 2 years ago

brillout commented 2 years ago

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:

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

mquandalle commented 2 years ago

Sounds similar to https://github.com/antfu/vite-node ?

brillout commented 2 years ago

@mquandalle Yes, but it needs to be built into Vite for https://github.com/vikejs/research/issues/3.

mkilpatrick commented 2 years ago

This would be awesome! I was just about to post about wanting to create a plugin that creates a server in middleware mode (ssr) and either works with Vite or allows you to replace the server with your own. This issue seems to fit that bill. In my scenario, I don't want the user to have to define a server.js though. I want it to be provided by my custom plugin out of the box.

Sort of on the same topic, but could it be possible to allow for a custom index.html (like ssr mode allows) but allow it to be passed to the vite dev server (instead of it assuming there's a local file at the root)? The only real reason I use ssr mode is because, similar to abstracting away server.js from users, I want to do the same for the index.html and entry.js. I've already accomplished this via my own custom package that people need to use. Would love to be able to do these things via a plugin or natively with Vite.

brillout commented 2 years ago

Alternatively to vite-node, there is also vavite.