Skip to content

Commit

Permalink
fix(serve): respect base config in serve mode (#470)
Browse files Browse the repository at this point in the history
Fixes #416

Signed-off-by: Gordon Smith <[email protected]>
  • Loading branch information
GordonSmith authored Jan 6, 2022
1 parent 444562c commit 08a0b12
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions src/node/serve/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ import compression from 'compression'
import { resolveConfig } from '../config'
import polka from 'polka'

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 {
root?: string
port?: number
Expand All @@ -11,6 +23,7 @@ export interface ServeOptions {
export async function serve(options: ServeOptions = {}) {
const port = options.port !== undefined ? options.port : 5000
const site = await resolveConfig(options.root, 'serve', 'production')
const base = trimChar(site?.site?.base ?? "", "/")

const compress = compression()
const serve = sirv(site.outDir, {
Expand All @@ -27,10 +40,19 @@ export async function serve(options: ServeOptions = {}) {
}
})

polka()
.use(compress, serve)
.listen(port, (err: any) => {
if (err) throw err
console.log(`Built site served at http://localhost:${port}/\n`)
})
if (base) {
polka()
.use(base, compress, serve)
.listen(port, (err: any) => {
if (err) throw err
console.log(`Built site served at http://localhost:${port}/${base}/\n`)
})
} else {
polka()
.use(compress, serve)
.listen(port, (err: any) => {
if (err) throw err
console.log(`Built site served at http://localhost:${port}/\n`)
})
}
}

0 comments on commit 08a0b12

Please sign in to comment.