如何将节点服务器与 Vue Vite 捆绑器一起使用

Dan*_*Dan 7 bundler vue.js vite

有人知道如何在端口 3000 上使用 Nodejs 服务器而不是 Vite 自己的前端开发服务器。我尝试了如下所有命令组合,但没有成功

vite
vite preview
vite preview --port:5000
Run Code Online (Sandbox Code Playgroud)

谢谢

2022 年 2 月 8 日更新
我找到了一种方法。我们必须在 vite 构建命令中添加 --watch 标志,例如:vite build --watch 这样 Vite 将仅捆绑对前端的更改并将其存储在文件夹中/dist,但它会像 Nodejs 一样监视外部服务器。这样我们就可以同时开发前端和后端文件并立即看到结果。我们必须单独启动服务器文件并从那里提供index.html。如果我们在服务器端使用 Nodejs 和 Express,我们还必须指向默认目录,/dist因为 Vite 会将捆绑文件放在那里,例如app.use(express.static(__dirname + '/dist'));. 节点将自动提供index.html此文件夹中的其他捆绑文件。

bec*_*hir 6

基本上,您将在服务器选项上middlewareMode设置:ssr

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()
Run Code Online (Sandbox Code Playgroud)

文档中对此进行了解释: https ://vitejs.dev/guide/ssr.html#setting-up-the-dev-server

Vite 2.x 更新

对于 Vite 2.x 设置server.middlewareModetrueappTypeto custom

  // ...
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom'
  })
Run Code Online (Sandbox Code Playgroud)