-
Notifications
You must be signed in to change notification settings - Fork 1
/
https.ts
59 lines (49 loc) · 1.99 KB
/
https.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
import { getPort, getSiteurl } from './pug/dotenv'
import _ from 'lodash'
import { fileURLToPath } from 'url'
import { promises as fsPromises } from 'fs'
import finalhandler from 'finalhandler'
import https from 'https'
import livereload from 'livereload'
import path from 'path'
import serveStatic from 'serve-static'
import watch from 'node-watch'
const __dirname = path.dirname(fileURLToPath(import.meta.url)) // eslint-disable-line @typescript-eslint/naming-convention
async function readMkcert (): Promise<{ cert: Buffer, key: Buffer }> {
try {
const [cert, key] = await Promise.all([
fsPromises.readFile(path.resolve(__dirname, './mkcert/cert.pem')),
fsPromises.readFile(path.resolve(__dirname, './mkcert/key.pem')),
])
return { cert, key }
} catch (err) {
throw new Error('Failed to load mkcert. Please run "yarn mkcert" first.')
}
}
async function main (): Promise<void> {
const publicDir = path.resolve(__dirname, './dist')
const httpsServer = https.createServer(await readMkcert(), (req, res) => {
serveStatic(publicDir, {
index: ['index.html', 'index.htm'],
})(req, res, finalhandler(req, res))
})
const livereloadServer = livereload.createServer({
port: getPort(),
server: httpsServer,
}) as LiveReloadServer1
livereloadServer._filterRefresh = (livereloadServer as any).filterRefresh
livereloadServer.filterRefresh = _.debounce((filepath: string) => { livereloadServer._filterRefresh?.(filepath) }, 1000)
livereloadServer.watch(publicDir)
console.log(`build finish. Visit: ${getSiteurl('/test.html')}`)
watch(['./pug'], { recursive: true }, async (e, name) => {
if (e !== 'update') return
const match = name.match(/^pug[/]src[/](.+)\.pug$/)
if (_.isNil(match)) return
console.log(getSiteurl(`./${match[1].replace(/\\/g, '/')}.html`))
})
}
type LiveReloadServer1 = livereload.LiveReloadServer & { _filterRefresh?: livereload.LiveReloadServer['filterRefresh'] }
main().catch(err => {
console.error(err)
process.exit(1)
})