為何捐款
API 瀏覽器
升級指南
NEW!
quasar.config 檔案
將專案轉換為搭配 Vite 的 CLI
瀏覽器相容性
支援 TypeScript
目錄結構
命令列表
CSS 預處理器
路由
懶加載 - 程式碼分割
處理資源
啟動檔案
預取功能
API 代理
處理 Vite
處理 process.env
使用 Pinia 進行狀態管理
使用 Vuex 進行狀態管理
Linter (程式碼檢查工具)
測試與稽核
開發行動應用程式
Ajax 請求
對外公開開發伺服器
Quasar CLI with Vite - @quasar/app-vite
SSR 網路伺服器

請注意,您產生的 /src-ssr 資料夾中包含一個名為 server.js 的檔案。此檔案定義了 SSR 網路伺服器的建立、管理和服務方式。您可以開始監聽連接埠,或為您的無伺服器基礎架構提供處理常式。這取決於您。

結構

/src-ssr/server.[js|ts] 檔案是一個簡單的 JavaScript/Typescript 檔案,用於啟動您的 SSR 網路伺服器,並定義網路伺服器如何啟動和處理請求,以及它匯出的內容(如果有的話)。

警告

/src-ssr/server.[js|ts] 檔案用於開發 (DEV) 和生產 (PROD) 環境,因此請小心設定。若要區分這兩種狀態,您可以使用 process∙env∙DEVprocess∙env∙PROD

/**
 * More info about this file:
 * https://v2.quasar.dev/quasar-cli-vite/developing-ssr/ssr-webserver
 *
 * Runs in Node context.
 */

/**
 * Make sure to yarn/npm/pnpm/bun install (in your project root)
 * anything you import here (except for express and compression).
 */
import express from 'express'
import compression from 'compression'

/**
 * Create your webserver and return its instance.
 * If needed, prepare your webserver to receive
 * connect-like middlewares.
 *
 * Should NOT be async!
 */
export function create (/* { ... } */) {
  const app = express()

  // attackers can use this header to detect apps running Express
  // and then launch specifically-targeted attacks
  app.disable('x-powered-by')

  // place here any middlewares that
  // absolutely need to run before anything else
  if (process.env.PROD) {
    app.use(compression())
  }

  return app
}

/**
 * You need to make the server listen to the indicated port
 * and return the listening instance or whatever you need to
 * close the server with.
 *
 * The "listenResult" param for the "close()" definition below
 * is what you return here.
 *
 * For production, you can instead export your
 * handler for serverless use or whatever else fits your needs.
 */
export async function listen ({ app, port, isReady, ssrHandler }) {
  await isReady()
  return await app.listen(port, () => {
    if (process.env.PROD) {
      console.log('Server listening at port ' + port)
    }
  })
}

/**
 * Should close the server and free up any resources.
 * Will be used on development only when the server needs
 * to be rebooted.
 *
 * Should you need the result of the "listen()" call above,
 * you can use the "listenResult" param.
 *
 * Can be async.
 */
export function close ({ listenResult }) {
  return listenResult.close()
}

const maxAge = process.env.DEV
  ? 0
  : 1000 * 60 * 60 * 24 * 30

/**
 * Should return middleware that serves the indicated path
 * with static content.
 */
export function serveStaticContent (path, opts) {
  return express.static(path, {
    maxAge,
    ...opts
  })
}

const jsRE = /\.js$/
const cssRE = /\.css$/
const woffRE = /\.woff$/
const woff2RE = /\.woff2$/
const gifRE = /\.gif$/
const jpgRE = /\.jpe?g$/
const pngRE = /\.png$/

/**
 * Should return a String with HTML output
 * (if any) for preloading indicated file
 */
export function renderPreloadTag (file) {
  if (jsRE.test(file) === true) {
    return `<link rel="modulepreload" href="${file}" crossorigin>`
  }

  if (cssRE.test(file) === true) {
    return `<link rel="stylesheet" href="${file}">`
  }

  if (woffRE.test(file) === true) {
    return `<link rel="preload" href="${file}" as="font" type="font/woff" crossorigin>`
  }

  if (woff2RE.test(file) === true) {
    return `<link rel="preload" href="${file}" as="font" type="font/woff2" crossorigin>`
  }

  if (gifRE.test(file) === true) {
    return `<link rel="preload" href="${file}" as="image" type="image/gif">`
  }

  if (jpgRE.test(file) === true) {
    return `<link rel="preload" href="${file}" as="image" type="image/jpeg">`
  }

  if (pngRE.test(file) === true) {
    return `<link rel="preload" href="${file}" as="image" type="image/png">`
  }

  return ''
}

提示

請記住,無論 listen() 函數傳回什麼(如果有的話),都會從您建置的 dist/ssr/index.js 中匯出。如果需要,您可以為無伺服器架構傳回您的 ssrHandler。

參數

export function <functionName> ({
  app, port, isReady, ssrHandler,
  resolve, publicPath, folders, render, serve
}) => {

物件詳情

{
  app,     // Expressjs app instance (or whatever you return from create())

  port,    // on production: process∙env∙PORT or quasar.config file > ssr > prodPort
           // on development: quasar.config file > devServer > port

  isReady, // Function to call returning a Promise
           // when app is ready to serve clients

  ssrHandler, // Prebuilt app handler if your serverless service
              // doesn't require a specific way to provide it.
              // Form: ssrHandler (req, res, next)
              // Tip: it uses isReady() under the hood already

  // all of the following are the same as
  // for the SSR middlewares (check its docs page);
  // normally you don't need these here
  // (use a real SSR middleware instead)
  resolve: {
    urlPath(path)
    root(arg1, arg2),
    public(arg1, arg2)
  },
  publicPath, // String
  folders: {
    root,     // String
    public    // String
  },
  render(ssrContext),
  serve: {
    static(path, opts),
    error({ err, req, res })
  }
}

用法

警告

  • 如果您從 node_modules 匯入任何內容,請確保該套件在 package.json > “dependencies” 中指定,而不是在 “devDependencies” 中。
  • 這裡通常不是新增中介軟體的地方(但您可以這麼做)。請改用 SSR 中介軟體 新增中介軟體。您可以設定 SSR 中介軟體僅在開發或僅在生產環境中執行。

取代 express.js

您可以使用任何其他與 connect API 相容的伺服器取代預設的 Express.js Node 伺服器。只需確保先 yarn/npm 安裝其套件。

src-ssr/server.[js|ts]

import connect from 'connect'

export function create (/* { ... } */) {
  const app = connect()

  // place here any middlewares that
  // absolutely need to run before anything else
  if (process.env.PROD) {
    app.use(compression())
  }

  return app
}

監聽連接埠

這是您在 Quasar CLI 專案中新增 SSR 支援時取得的預設選項。它會開始監聽設定的連接埠 (process∙env∙PORT 或 quasar.config 檔案 > ssr > prodPort)。

src-ssr/server.[js|ts]

export async function listen ({ app, port, isReady }) {
  await isReady()
  return await app.listen(port, () => {
    if (process.env.PROD) {
      console.log('Server listening at port ' + port)
    }
  })
}

無伺服器

如果您有無伺服器基礎架構,那麼通常需要匯出處理常式,而不是開始監聽連接埠。

假設您的無伺服器服務要求您

module.exports.handler = __your_handler__

那麼您需要做的是

src-ssr/server.[js|ts]

export async function listen ({ app, port, ssrHandler }) {
  if (process.env.DEV) {
    await isReady()
    return await app.listen(port, () => {
      if (process.env.PROD) {
        console.log('Server listening at port ' + port)
      }
    })
  }
  else { // in production
    // "ssrHandler" is a prebuilt handler which already
    // waits for all the middlewares to run before serving clients

    // whatever you return here is equivalent to module.exports.<key> = <value>
    return { handler: ssrHandler }
  }
}

請注意,提供的 ssrHandler 是 `(req, res, next) => void` 形式的函數。如果您需要匯出 `(event, context, callback) => void` 形式的處理常式,那麼您很可能需要使用 serverless-http 套件(請參閱下方)。

範例:serverless-http

您需要手動 yarn/npm 安裝 serverless-http 套件。

src-ssr/server.[js|ts]

import serverless from 'serverless-http'

export async function listen (({ app, port, ssrHandler }) => {
  if (process.env.DEV) {
    await isReady()
    return await app.listen(port, () => {
      // we're ready to serve clients
    })
  }
  else { // in production
    return { handler: serverless(ssrHandler) }
  }
})

範例:Firebase 函數

src-ssr/server.[js|ts]

import * as functions from 'firebase-functions'

export async function listen (({ app, port, ssrHandler }) => {
  if (process.env.DEV) {
    await isReady()
    return await app.listen(port, () => {
      // we're ready to serve clients
    })
  }
  else { // in production
    return {
      handler: functions.https.onRequest(ssrHandler)
    }
  }
})