-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
spa.js
214 lines (179 loc) · 6.39 KB
/
spa.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { extname } from 'path'
import cloneDeep from 'lodash/cloneDeep'
import VueMeta from 'vue-meta'
import { createRenderer } from 'vue-server-renderer'
import LRU from 'lru-cache'
import devalue from '@nuxt/devalue'
import { TARGETS, isModernRequest } from '@nuxt/utils'
import BaseRenderer from './base'
export default class SPARenderer extends BaseRenderer {
constructor (serverContext) {
super(serverContext)
this.cache = new LRU()
this.vueMetaConfig = {
ssrAppId: '1',
...this.options.vueMeta,
keyName: 'head',
attribute: 'data-n-head',
ssrAttribute: 'data-n-head-ssr',
tagIDKeyName: 'hid'
}
}
createRenderer () {
return createRenderer()
}
async render (renderContext) {
const { url = '/', req = {} } = renderContext
const modernMode = this.options.modern
const modern = (modernMode && this.options.target === TARGETS.static) || isModernRequest(req, modernMode)
const cacheKey = `${modern ? 'modern:' : 'legacy:'}${url}`
let meta = this.cache.get(cacheKey)
if (meta) {
// Return a copy of the content, so that future
// modifications do not effect the data in cache
return cloneDeep(meta)
}
meta = {
HTML_ATTRS: '',
HEAD_ATTRS: '',
BODY_ATTRS: '',
HEAD: '',
BODY_SCRIPTS_PREPEND: '',
BODY_SCRIPTS: ''
}
if (this.options.features.meta) {
// Get vue-meta context
renderContext.head = typeof this.options.head === 'function'
? this.options.head()
: cloneDeep(this.options.head)
}
// Allow overriding renderContext
await this.serverContext.nuxt.callHook('vue-renderer:spa:prepareContext', renderContext)
if (this.options.features.meta) {
const m = VueMeta.generate(renderContext.head || {}, this.vueMetaConfig)
// HTML_ATTRS
meta.HTML_ATTRS = m.htmlAttrs.text()
// HEAD_ATTRS
meta.HEAD_ATTRS = m.headAttrs.text()
// BODY_ATTRS
meta.BODY_ATTRS = m.bodyAttrs.text()
// HEAD tags
meta.HEAD =
m.title.text() +
m.meta.text() +
m.link.text() +
m.style.text() +
m.script.text() +
m.noscript.text()
// Add <base href=""> meta if router base specified
if (this.options._routerBaseSpecified) {
meta.HEAD += `<base href="${this.options.router.base}">`
}
// BODY_SCRIPTS (PREPEND)
meta.BODY_SCRIPTS_PREPEND =
m.meta.text({ pbody: true }) +
m.link.text({ pbody: true }) +
m.style.text({ pbody: true }) +
m.script.text({ pbody: true }) +
m.noscript.text({ pbody: true })
// BODY_SCRIPTS (APPEND)
meta.BODY_SCRIPTS =
m.meta.text({ body: true }) +
m.link.text({ body: true }) +
m.style.text({ body: true }) +
m.script.text({ body: true }) +
m.noscript.text({ body: true })
}
// Resources Hints
meta.resourceHints = ''
const { resources: { modernManifest, clientManifest } } = this.serverContext
const manifest = modern ? modernManifest : clientManifest
const { shouldPreload, shouldPrefetch } = this.options.render.bundleRenderer
if (this.options.render.resourceHints && manifest) {
const publicPath = manifest.publicPath || '/_nuxt/'
// Preload initial resources
if (Array.isArray(manifest.initial)) {
const { crossorigin } = this.options.render
const cors = `${crossorigin ? ` crossorigin="${crossorigin}"` : ''}`
meta.preloadFiles = manifest.initial
.map(SPARenderer.normalizeFile)
.filter(({ fileWithoutQuery, asType }) => shouldPreload(fileWithoutQuery, asType))
.map(file => ({ ...file, modern }))
meta.resourceHints += meta.preloadFiles
.map(({ file, extension, fileWithoutQuery, asType, modern }) => {
let extra = ''
if (asType === 'font') {
extra = ` type="font/${extension}"${cors ? '' : ' crossorigin'}`
}
const rel = modern && asType === 'script' ? 'modulepreload' : 'preload'
return `<link rel="${rel}"${cors} href="${publicPath}${file}"${
asType !== '' ? ` as="${asType}"` : ''}${extra}>`
})
.join('')
}
// Prefetch async resources
if (Array.isArray(manifest.async)) {
meta.resourceHints += manifest.async
.map(SPARenderer.normalizeFile)
.filter(({ fileWithoutQuery, asType }) => shouldPrefetch(fileWithoutQuery, asType))
.map(({ file }) => `<link rel="prefetch" href="${publicPath}${file}">`)
.join('')
}
// Add them to HEAD
if (meta.resourceHints) {
meta.HEAD += meta.resourceHints
}
}
// Serialize state (runtime config)
let APP = `${meta.BODY_SCRIPTS_PREPEND}<div id="${this.serverContext.globals.id}">${this.serverContext.resources.loadingHTML}</div>${meta.BODY_SCRIPTS}`
const payload = {
config: renderContext.runtimeConfig.public
}
if (renderContext.staticAssetsBase) {
payload.staticAssetsBase = renderContext.staticAssetsBase
}
APP += `<script>window.${this.serverContext.globals.context}=${devalue(payload)}</script>`
// Prepare template params
const templateParams = {
...meta,
APP,
ENV: this.options.env
}
// Call spa:templateParams hook
await this.serverContext.nuxt.callHook('vue-renderer:spa:templateParams', templateParams)
// Render with SPA template
const html = this.renderTemplate(this.serverContext.resources.spaTemplate, templateParams)
const content = {
html,
preloadFiles: meta.preloadFiles || []
}
// Set meta tags inside cache
this.cache.set(cacheKey, content)
// Return a copy of the content, so that future
// modifications do not effect the data in cache
return cloneDeep(content)
}
static normalizeFile (file) {
const withoutQuery = file.replace(/\?.*/, '')
const extension = extname(withoutQuery).slice(1)
return {
file,
extension,
fileWithoutQuery: withoutQuery,
asType: SPARenderer.getPreloadType(extension)
}
}
static getPreloadType (ext) {
if (ext === 'js') {
return 'script'
} else if (ext === 'css') {
return 'style'
} else if (/jpe?g|png|svg|gif|webp|ico|avif/.test(ext)) {
return 'image'
} else if (/woff2?|ttf|otf|eot/.test(ext)) {
return 'font'
} else {
return ''
}
}
}