如何基于 Vite 開發(fā) React 和 Koa 全棧程序

基于 Vite 開發(fā) React 和 Koa 全棧程序

創(chuàng)建一個(gè)新的 Vite 應(yīng)用

pnpm create vite react-kao-app -- --template react

進(jìn)入項(xiàng)目安裝依賴:

cd react-koa-app
pnpm i

項(xiàng)目結(jié)構(gòu)如下:


image.png

配置 vite

修改包的入口配置為 src/main.jsx,而不是根目錄下默認(rèn)的 index.html

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  // 新增 build 配置
  build: {
    manifest: true,
    rollupOptions: {
      input: './src/main.jsx'
    }
  }
})

重新組織項(xiàng)目結(jié)構(gòu)

mv index.html public/

然后覆蓋 index.html 文件的內(nèi)容為:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module">
      import RefreshRuntime from 'http://localhost:5173/@react-refresh'
      RefreshRuntime.injectIntoGlobalHook(window)
      window.$RefreshReg$ = () => {}
      window.$RefreshSig$ = () => type => type
      window.__vite_plugin_react_preamble_installed__ = true
    </script>
    <script type="module" src="http://localhost:5173/src/main.jsx"></script>
  </body>
</html>

@react-refresh相關(guān)的代碼是因?yàn)関ite啟動(dòng)后在index.html中注入這些代碼來實(shí)現(xiàn)HMR,因?yàn)槲沂峭ㄟ^node的服務(wù)讀取的html文件,所以需要手動(dòng)注入。

創(chuàng)建服務(wù)

touch server.js
pnpm add koa

編寫 server.js

const Koa = require('koa')
const path = require('path')
const sendfile = require('koa-sendfile')
const serve = require('koa-static')
const app = new Koa()

// static
app.use(serve(path.join(__dirname, 'public')))

// 404
app.use(async (ctx, next) => {
  await next()

  if (ctx.status === 404) {
    await sendfile(ctx, path.resolve(__dirname, 'public/index.html'))
  }
})

app.listen(5000, () => {
  console.log()
  console.log('App runing in port 5000...')
  console.log()
  console.log(`  > Local: \x1b[36mhttp://localhost:\x1b[1m5000/\x1b[0m`)
})

這樣啟動(dòng)服務(wù)后,讀取的是前端的 html 文件。但是有個(gè)問題,靜態(tài)資源(圖片、視頻等)vite會(huì)處理成URL,比如 import logo from './assets/react.svg'會(huì)處理成/src/assets/react.svg,但是node服務(wù)下沒有該目錄,所以我通過正則匹配路由然后重新指向vite服務(wù)來解決這個(gè)問題。定義特定格式的路由處理中間件:

const Router = require('@koa/router')

const staticReg = /\/.+\.(svg|png|jpg|png|jpeg|mp4|ogv)$/ // 還可以添加其他格式
const router = new Router()

router.get(staticReg, (ctx, next) => {
  ctx.redirect(`http://localhost:5173${ctx.path}`)
})

module.exports = router

在 server 中添加:

const assets = require('./server/assets-router')
// assets
app.use(assets.routes()).use(assets.allowedMethods())

創(chuàng)建 API 接口

const Router = require('@koa/router')
const router = new Router()

router.get('/api/v1', (ctx, next) => {
  ctx.body = [
    {
      id: 1,
      name: 'jack',
      age: 11
    },
    {
      id: 2,
      name: 'rose',
      age: 12
    },
    {
      id: 3,
      name: 'mike',
      age: 13
    }
  ]
})

module.exports = router

server.js 中添加:

const router = require('./server/api-router.js')
// api
app.use(router.routes()).use(router.allowedMethods())

獲取接口信息

App.jsx 中調(diào)用接口:

import { useState, useEffect } from 'react'

function App() {
  const [list, setList] = useState([])

  useEffect(() => {
    fetch('/api/v1')
      .then(res => res.json())
      .then(res => setList(res))
  }, [])

  return (
    <div className='App'>
      <ul>
        {list.map(({ id, name, age }) => (
          <li key={id}>
            id: {id} -- name: {name} -- age: {age}
          </li>
        ))}
      </ul>
    </div>
  )
}

export default App

nodemon 和 concurrently

nodemon 可以實(shí)時(shí)重啟服務(wù),concurrently 可以同時(shí)運(yùn)行多個(gè)命令:

pnpm add concurrently nodemon -D

運(yùn)行程序

在 package.json 文件中添加下一個(gè) scripts:

"dev": "clear & concurrently 'vite' 'nodemon server.js'"

運(yùn)行程序:

pnpm dev

瀏覽器打開 http://localhost:5000。頁面展示和接口調(diào)用均正常:

image.png

至此,基于 vite 的 react + koa 的全棧項(xiàng)目搭建完成。

問題:為什么要單獨(dú)處理 img video 等靜態(tài)資源,而 js 以及 在 js 中引入的 css 不需要處理?

這是因?yàn)殪o態(tài)資源在 js 導(dǎo)入后被 vite 解析成 URL,比如:/src/assets/react.svg,在 html 中加載的時(shí)候該路徑的根目錄是基于端口 5000 的后端服務(wù)的,所以單獨(dú)做了處理,判斷如果是靜態(tài)資源就轉(zhuǎn)發(fā)到客戶端服務(wù)上,而 js 導(dǎo)入的 js、css 是基于 script 的 src 的,所以資源從前端 vite 起的服務(wù)中加載:

<script type='module' src='http://localhost:5173/src/main.jsx'>
  import foo from './foo.js'
</script>

import foo from './foo.js' 會(huì)被 vite 處理成 /src/foo.js,瀏覽器獲取該資源的完整地址是基于 script 的 src 的,即:http://localhost:5173/src/foo.js

image.png

ps:為了避免與其他構(gòu)建工具的端口產(chǎn)生沖突,vite3.0 默認(rèn)的端口由之前的 3000 改為 5173。

通過 github 獲取完整代碼代碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容