-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
serve.ts
75 lines (67 loc) · 1.92 KB
/
serve.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import compression from 'compression'
import fs from 'fs-extra'
import path from 'path'
import polka, { type IOptions } from 'polka'
import sirv, { type RequestHandler } from 'sirv'
import { resolveConfig } from '../config'
function trimChar(str: string, char: string) {
while (str.charAt(0) === char) {
str = str.substring(1)
}
while (str.charAt(str.length - 1) === char) {
str = str.substring(0, str.length - 1)
}
return str
}
export interface ServeOptions {
base?: string
root?: string
port?: number
configFile?: string
}
export async function serve(options: ServeOptions = {}) {
const port = options.port ?? 4173
const config = await resolveConfig(
options.root,
'serve',
'production',
options.configFile
)
const base = trimChar(options?.base ?? config?.site?.base ?? '', '/')
const notAnAsset = (pathname: string) =>
!pathname.includes(`/${config.assetsDir}/`)
const notFound = fs.readFileSync(path.resolve(config.outDir, './404.html'))
const onNoMatch: IOptions['onNoMatch'] = (req, res) => {
res.statusCode = 404
if (notAnAsset(req.path)) res.write(notFound.toString())
res.end()
}
const compress = compression() as RequestHandler
const serve = sirv(config.outDir, {
etag: true,
maxAge: 31536000,
immutable: true,
setHeaders(res, pathname) {
if (notAnAsset(pathname)) {
// force server validation for non-asset files since they
// are not fingerprinted
res.setHeader('cache-control', 'no-cache')
}
}
})
if (base) {
return polka({ onNoMatch })
.use(base, compress, serve)
.listen(port, () => {
config.logger.info(
`Built site served at http://localhost:${port}/${base}/`
)
})
} else {
return polka({ onNoMatch })
.use(compress, serve)
.listen(port, () => {
config.logger.info(`Built site served at http://localhost:${port}/`)
})
}
}