注意你生成的/src-ssr
包含一个名为server.js
的文件。这个文件定义了如何创建、管理和服务你的SSR webserver。你可以开始监听一个端口,或者为你的无服务器基础设施提供一个处理程序来使用。这由你决定。
剖析
/src-ssr/server.[js|ts]
文件是一个简单的JavaScript/Typescript文件,它启动了你的SSR webserver,并定义了你的webserver如何启动和处理请求,以及它输出了什么(如果输出了什么)。
WARNING
/src-ssr/server.[js|ts]
文件同时用于DEV和PROD,所以请注意你的配置方式。为了区分这两种状态,你可以使用false
和true
。
/**
* More info about this file:
* https://v2.quasar.dev/quasar-cli-vite/developing-ssr/ssr-webserver
*
* Runs in Node context.
*/
/**
* Make sure to yarn add / npm 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 ''
}
TIP
记住,无论listen()
函数返回什么(如果有的话),都将从你构建的dist/ssr/index.js
中导出。如果你需要,你可以为无服务器架构返回你的ssrHandler。
Parameters
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.js > ssr > prodPort
// on development: quasar.config.js > 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 })
}
}
用法
WARNING
- 如果你从node_modules中导入任何东西,那么请确保软件包在package.json > "dependencies "中指定,而不是在 "devDependencies "中。
- 这里通常不是添加中间件的地方(但你可以这样做)。通过使用[SSR Middlewares](/quasar-cli-vite/developing-ssr/ssr-middleware)来添加中间件。你可以将SSR中间件配置为只为开发或只为生产运行。
替换Express.js
你可以用任何其他connect API兼容的Node服务器替换默认的Express.js。只需确保先用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.js > 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__
Then what you’d need to do is:
// 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'
import { ssrProductionExport } from 'quasar/wrappers'
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
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, () => {
if (process.env.PROD) {
console.log('Server listening at port ' + port)
}
})
}
else { // in production
return {
handler: functions.https.onRequest(ssrHandler)
}
}
})