-
-
Notifications
You must be signed in to change notification settings - Fork 33.7k
/
Copy pathindex.js
220 lines (202 loc) · 6.63 KB
/
index.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
215
216
217
218
219
220
/* @flow */
const path = require('path')
const serialize = require('serialize-javascript')
import { isJS, isCSS } from '../util'
import TemplateStream from './template-stream'
import { parseTemplate } from './parse-template'
import { createMapper } from './create-async-file-mapper'
import type { ParsedTemplate } from './parse-template'
import type { AsyncFileMapper } from './create-async-file-mapper'
type TemplateRendererOptions = {
template: ?string;
inject?: boolean;
clientManifest?: ClientManifest;
shouldPreload?: (file: string, type: string) => boolean;
};
export type ClientManifest = {
publicPath: string;
all: Array<string>;
initial: Array<string>;
async: Array<string>;
modules: {
[id: string]: Array<number>;
},
hasNoCssVersion?: {
[file: string]: boolean;
}
};
export default class TemplateRenderer {
options: TemplateRendererOptions;
inject: boolean;
parsedTemplate: ParsedTemplate | null;
publicPath: string;
clientManifest: ClientManifest;
preloadFiles: Array<string>;
prefetchFiles: Array<string>;
mapFiles: AsyncFileMapper;
constructor (options: TemplateRendererOptions) {
this.options = options
this.inject = options.inject !== false
// if no template option is provided, the renderer is created
// as a utility object for rendering assets like preload links and scripts.
this.parsedTemplate = options.template
? parseTemplate(options.template)
: null
// extra functionality with client manifest
if (options.clientManifest) {
const clientManifest = this.clientManifest = options.clientManifest
this.publicPath = clientManifest.publicPath.replace(/\/$/, '')
// preload/prefetch drectives
this.preloadFiles = clientManifest.initial
this.prefetchFiles = clientManifest.async
// initial async chunk mapping
this.mapFiles = createMapper(clientManifest)
}
}
bindRenderFns (context: Object) {
const renderer: any = this
;['ResourceHints', 'State', 'Scripts', 'Styles'].forEach(type => {
context[`render${type}`] = renderer[`render${type}`].bind(renderer, context)
})
}
// render synchronously given rendered app content and render context
renderSync (content: string, context: ?Object) {
const template = this.parsedTemplate
if (!template) {
throw new Error('renderSync cannot be called without a template.')
}
context = context || {}
if (this.inject) {
return (
template.head(context) +
(context.head || '') +
this.renderResourceHints(context) +
this.renderStyles(context) +
template.neck(context) +
content +
this.renderState(context) +
this.renderScripts(context) +
template.tail(context)
)
} else {
return (
template.head(context) +
template.neck(context) +
content +
template.tail(context)
)
}
}
renderStyles (context: Object): string {
const cssFiles = this.clientManifest
? this.clientManifest.all.filter(isCSS)
: []
return (
// render links for css files
(cssFiles.length
? cssFiles.map(file => `<link rel="stylesheet" href="${this.publicPath}/${file}">`).join('')
: '') +
// context.styles is a getter exposed by vue-style-loader which contains
// the inline component styles collected during SSR
(context.styles || '')
)
}
renderResourceHints (context: Object): string {
return this.renderPreloadLinks(context) + this.renderPrefetchLinks(context)
}
renderPreloadLinks (context: Object): string {
const usedAsyncFiles = this.getUsedAsyncFiles(context)
if (this.preloadFiles || usedAsyncFiles) {
return (this.preloadFiles || []).concat(usedAsyncFiles || []).map(file => {
let extra = ''
const withoutQuery = file.replace(/\?.*/, '')
const ext = path.extname(withoutQuery).slice(1)
const type = getPreloadType(ext)
const shouldPreload = this.options.shouldPreload
// by default, we only preload scripts or css
if (!shouldPreload && type !== 'script' && type !== 'style') {
return ''
}
// user wants to explicitly control what to preload
if (shouldPreload && !shouldPreload(withoutQuery, type)) {
return ''
}
if (type === 'font') {
extra = ` type="font/${ext}" crossorigin`
}
return `<link rel="preload" href="${
this.publicPath}/${file
}"${
type !== '' ? ` as="${type}"` : ''
}${
extra
}>`
}).join('')
} else {
return ''
}
}
renderPrefetchLinks (context: Object): string {
if (this.prefetchFiles) {
const usedAsyncFiles = this.getUsedAsyncFiles(context)
const alreadyRendered = file => {
return usedAsyncFiles && usedAsyncFiles.some(f => f === file)
}
return this.prefetchFiles.map(file => {
if (!alreadyRendered(file)) {
return `<link rel="prefetch" href="${this.publicPath}/${file}" as="script">`
} else {
return ''
}
}).join('')
} else {
return ''
}
}
renderState (context: Object): string {
return context.state
? `<script>window.__INITIAL_STATE__=${
serialize(context.state, { isJSON: true })
}</script>`
: ''
}
renderScripts (context: Object): string {
if (this.clientManifest) {
const initial = this.clientManifest.initial
const async = this.getUsedAsyncFiles(context)
const needed = [initial[0]].concat(async || [], initial.slice(1))
return needed.filter(isJS).map(file => {
return `<script src="${this.publicPath}/${file}"></script>`
}).join('')
} else {
return ''
}
}
getUsedAsyncFiles (context: Object): ?Array<string> {
if (!context._mappedfiles && context._registeredComponents && this.mapFiles) {
context._mappedFiles = this.mapFiles(Array.from(context._registeredComponents))
}
return context._mappedFiles
}
// create a transform stream
createStream (context: ?Object): TemplateStream {
if (!this.parsedTemplate) {
throw new Error('createStream cannot be called without a template.')
}
return new TemplateStream(this, this.parsedTemplate, context || {})
}
}
function getPreloadType (ext: string): string {
if (ext === 'js') {
return 'script'
} else if (ext === 'css') {
return 'style'
} else if (/jpe?g|png|svg|gif|webp|ico/.test(ext)) {
return 'image'
} else if (/woff2?|ttf|otf|eot/.test(ext)) {
return 'font'
} else {
// not exhausting all possbilities here, but above covers common cases
return ''
}
}