-
Notifications
You must be signed in to change notification settings - Fork 175
/
renderStatic.js
62 lines (58 loc) · 2.21 KB
/
renderStatic.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
'use strict'
// Use react-snap to crawl from the specified URL paths and prerender HTML for those pages.
// Since paths to JS/CSS assets are relative to webpack publicPath, and not relative to
// the location of the page being prerendered, those src/href paths need to be prefixed with
// the correct number of `../`'s to reference the project root.
//
// For example, the output of react-snap for a page at http:https://localhost:PORT/path/to/page/
// will have a <script src="/bundle.js"/> (webpack publicPath is `/`). But it should have
// the path: <script src="../../../bundle.js"/> to point to the bundle.js at the project root.
//
// React-snap does not yet support this, see https://github.com/stereobooster/react-snap/issues/397
// so we will re-parse the HTML files and replace their URLs with relative ones.
const { run } = require('react-snap')
const path = require('path')
const fs = require('fs-extra')
const globby = require('globby')
const rehype = require('rehype')
const rehypeUrls = require('rehype-urls')
const outputPath = 'dist'
const outputPathAbs = path.join(__dirname, outputPath)
run({
source: outputPath,
include: ['/', '/create/'],
skipThirdPartyRequests: true,
})
.then(() => globby(path.join(outputPathAbs, '**/*.html')))
.then(pagePaths =>
Promise.all(
pagePaths.map(pagePath =>
fs.readFile(pagePath, 'utf8').then(page => {
// convert filesystem path to URL relative path
const relativePath =
path
.relative(path.dirname(pagePath), outputPathAbs)
// split & join in case you have a Windows path
.split(path.sep)
.join('/') || '.'
const relativizeUrl = url => {
if (url.host) {
return url.href
} else {
return `${relativePath}${url.path}`
}
}
return rehype()
.use(rehypeUrls, relativizeUrl)
.process(page)
.then(newPageVFile => {
console.log(
`PRERENDER: prefixing links in ${pagePath} with "${relativePath}/"`
)
return fs.writeFile(pagePath, newPageVFile.contents)
})
})
)
)
)
.catch(console.error)