Dan
Dan

Reputation: 690

How to use node server with Vue Vite bundler

Does someone know how to use Nodejs server instead of Vite own frontend dev server on the port 3000. I tried all command combinations like those below but with no success

vite
vite preview
vite preview --port:5000

Thanks

UPDATE Feb 8-th 2022
I have found a way. We have to add flag --watch to the vite build command, like: vite build --watch That way Vite will bundle only changes to the front-end and store it in the /dist folder but it will watch outside server like Nodejs. That way we can develop both front and back end file simultaneously and see the result immediately. We have to launch server file separately and serve index.html from there. If we use Nodejs and Express on the server side we also have to point default directory to be /dist because Vite will put bundled files there, like app.use(express.static(__dirname + '/dist'));. node will automatically serve index.html and other bundled files from this folder.

Upvotes: 7

Views: 15615

Answers (2)

rackable
rackable

Reputation: 1001

See this example for another approach: https://github.com/frameable/vite-vue-express-example

This way supports live updates with HMR in development, and runs in a single node process so you don't need to coordinate backend and dev server separately.

Upvotes: 0

bechir
bechir

Reputation: 459

Basically you will set the middlewareMode to ssr on the server options:

const fs = require('fs')
const path = require('path')
const express = require('express')
const { createServer: createViteServer } = require('vite')

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

  // Create Vite server in middleware mode. This disables Vite's own HTML
  // serving logic and let the parent server take control.
  //
  // If you want to use Vite's own HTML serving logic (using Vite as
  // a development middleware), using 'html' instead.
  const vite = await createViteServer({
    server: { middlewareMode: 'ssr' }
  })
  // use vite's connect instance as middleware
  app.use(vite.middlewares)

  app.use('*', async (req, res) => {
    // serve index.html - we will tackle this next
  })

  app.listen(3000)
}

createServer()

This is explained in the doc: https://vitejs.dev/guide/ssr.html#setting-up-the-dev-server

Update for Vite 2.x

For Vite 2.x set server.middlewareMode to true and appType to custom:

  // ...
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom'
  })

Upvotes: 6

Related Questions