/
gatsby-ssr.js
64 lines (59 loc) · 1.69 KB
/
gatsby-ssr.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
const _ = require(`lodash`)
const fs = require(`fs`)
const React = require(`react`)
const { guess } = require(`guess-webpack/api`)
function urlJoin(...parts) {
return parts.reduce((r, next) => {
const segment = next == null ? `` : String(next).replace(/^\/+/, ``)
return segment ? `${r.replace(/\/$/, ``)}/${segment}` : r
}, ``)
}
let s
const readStats = () => {
if (s) {
return s
} else {
s = JSON.parse(
fs.readFileSync(`${process.cwd()}/public/webpack.stats.json`, `utf-8`)
)
return s
}
}
exports.onRenderBody = (
{ setHeadComponents, pathname, pathPrefix, loadPageDataSync },
pluginOptions
) => {
if (
process.env.NODE_ENV === `production` ||
process.env.NODE_ENV === `test`
) {
const stats = readStats()
const matchedPaths = Object.keys(
guess({ path: pathname, threshold: pluginOptions.minimumThreshold })
)
if (!_.isEmpty(matchedPaths)) {
const matchedPages = matchedPaths.map(loadPageDataSync)
let componentUrls = []
matchedPages.forEach(p => {
if (p && p.componentChunkName) {
const fetchKey = `assetsByChunkName[${p.componentChunkName}]`
const chunks = _.get(stats, fetchKey)
componentUrls = [...componentUrls, ...chunks]
}
})
componentUrls = _.uniq(componentUrls)
const components = componentUrls.map(c =>
React.createElement(`Link`, {
as: c.slice(-2) === `js` ? `script` : undefined,
rel:
c.slice(-2) === `js` ? `prefetch` : `prefetch alternate stylesheet`,
key: c,
href: urlJoin(pathPrefix, c),
})
)
setHeadComponents(components)
}
return true
}
return false
}