This repository was archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.js
More file actions
82 lines (65 loc) · 1.73 KB
/
export.js
File metadata and controls
82 lines (65 loc) · 1.73 KB
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
const path = require('path')
const fetch = require('node-fetch')
const fs = require('fs-extra')
module.exports = function handleExport(config = {}) {
if (process.env.APP_EXPORT!=='1' || !config.routes) return
const {
dest, // process.env.APP_PUBLIC_DIR in the app
routes
} = config
if (!dest) {
console.error('Export destination must be passed in "dest" property')
process.exit()
return
}
const port = process.env.PORT || 3000
const baseUrl = `http://localhost:${port}`
// After next tick to ensure server is listening
setTimeout(function() {
console.log('Export from', baseUrl)
exportRoutes({
port,
dest,
baseUrl,
routes
}).then(() => {
console.log('Exported to', path.relative(process.cwd(), dest))
process.exit()
}).catch(e => {
console.error('Export failed', e)
process.exit()
})
}, 0)
}
const getRoute = (route) => new Promise((resolve, reject) => {
fetch(route)
.then(res => res.text())
.then(resolve)
.catch(reject)
})
async function exportRoutes({
dest,
baseUrl,
routes
}) {
for (const {
path: route,
routes: childRoutes
} of [...routes, { path: '/404' }]) {
if (!route) continue
console.log(`Export ${route}`)
const html = await getRoute(`${baseUrl}${route}`)
const routeTargetDir = route==='/404' ? dest : path.join(dest, route)
const routeTargetFile = path.join(routeTargetDir,
route==='/404' ? '404.html' : 'index.html'
)
await fs.ensureDir(routeTargetDir)
await fs.writeFile(routeTargetFile, html, 'utf8')
if (!childRoutes) continue
await exportRoutes({
dest: `${dest}${route}`,
baseUrl: `${baseUrl}${route}`,
routes: childRoutes
})
}
}