-
-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathprerender.js
107 lines (95 loc) · 3.63 KB
/
prerender.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import fs from 'fs'
import path from 'path'
import { Readable } from 'stream'
import { fileURLToPath } from 'url'
import { build } from 'vite'
import { SitemapStream, streamToPromise, EnumChangefreq } from 'sitemap'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const toAbsolute = (_path) => path.resolve(__dirname, _path)
const packageJSON = JSON.parse(fs.readFileSync(toAbsolute('package.json'), 'utf-8'))
const projectsJSON = JSON.parse(fs.readFileSync(toAbsolute('projects.json'), 'utf-8'))
const INDEX_ROUTE = '/'
const PAGE_ROUTES = Object.values(projectsJSON).map((project) => `/${project.route}`)
const ROUTES = [INDEX_ROUTE, ...PAGE_ROUTES]
const renderRedirectionHTML = (url) => `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="refresh" content="0; url='${url}'" />
</head>
</html>
`
try {
// empty dist dir
fs.rmSync(toAbsolute('dist'), { recursive: true, force: true })
console.log('1. Client render bundling...\n')
await build({ build: { emptyOutDir: true } })
console.info('\nClient bundle done.\n')
console.log('2. Server render bundling...\n')
await build({
build: {
ssr: true,
minify: false,
manifest: false,
emptyOutDir: false,
ssrEmitAssets: false,
copyPublicDir: false,
outDir: toAbsolute('dist/ssr'),
rollupOptions: {
input: toAbsolute('src/ssr.ts')
}
}
})
console.info('\nServer render bundle done.\n')
// MARK: after CSR bundled & before pre-render routes
const template = fs.readFileSync(toAbsolute('dist/index.html'), 'utf-8')
const { render } = await import('./dist/ssr/ssr.js')
let appStoreCache = null
// pre-render each route...
for (const url of ROUTES) {
const { appHTML, heads, storeCache } = await render(url, appStoreCache)
// cache the first render store data
appStoreCache = storeCache
const html = template
.replace(/<title>[\s\S]*<\/title>/, '')
.replace(`<html`, () => `<html ${heads.htmlAttrs} `)
.replace(`<head>`, () => `<head>\n${heads.headTags}`)
.replace(`<body>`, () => `<body ${heads.bodyAttrs}>`)
.replace(`<!--app-html-->`, () => appHTML)
.replace(`</body>`, () => `\n${heads.bodyTags}\n</body>`)
// ✅ https://github.surmon.me/xxx
// ❌ https://github.surmon.me/xxx/
// 🔗 https://ahrefs.com/blog/trailing-slash/
const fileName = `dist${url === INDEX_ROUTE ? '/index' : url}`
fs.writeFileSync(toAbsolute(`${fileName}.html`), html)
if (url !== INDEX_ROUTE) {
// redirect `x/` to 'x'
fs.mkdirSync(toAbsolute(`${fileName}/`), { recursive: true })
fs.writeFileSync(toAbsolute(`${fileName}/index.html`), renderRedirectionHTML(url))
}
console.log('pre-rendered:', url)
}
fs.rmSync(toAbsolute('dist/ssr'), { recursive: true, force: true })
console.info(`\n${ROUTES.length} pages has been generated.`)
// sitemap each route...
const sitemapStream = new SitemapStream({
hostname: packageJSON.homepage
})
const sitemapItemList = [
{ url: packageJSON.homepage, changefreq: EnumChangefreq.NEVER, priority: 1 },
...ROUTES.filter((route) => route !== INDEX_ROUTE).map((route) => ({
url: route,
changefreq: EnumChangefreq.MONTHLY,
priority: 1.0
}))
]
const finallySitemapStream = Readable.from(sitemapItemList).pipe(sitemapStream)
const sitemapXML = await streamToPromise(finallySitemapStream).then((data) => data.toString())
fs.writeFileSync(toAbsolute(`dist/sitemap.xml`), sitemapXML)
console.info(`Sitemap has been generated.`)
process.exit(0)
} catch (error) {
console.error('Generate ERROR!', error)
process.exit(1)
}