/
indexHtml.ts
209 lines (187 loc) · 5.79 KB
/
indexHtml.ts
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
import fs from 'fs'
import path from 'path'
import MagicString from 'magic-string'
import type { AttributeNode, ElementNode } from '@vue/compiler-dom'
import { NodeTypes } from '@vue/compiler-dom'
import type { Connect } from 'types/connect'
import type { IndexHtmlTransformHook } from '../../plugins/html'
import {
addToHTMLProxyCache,
applyHtmlTransforms,
assetAttrsConfig,
getScriptInfo,
resolveHtmlTransforms,
traverseHtml
} from '../../plugins/html'
import type { ResolvedConfig, ViteDevServer } from '../..'
import { send } from '../send'
import { CLIENT_PUBLIC_PATH, FS_PREFIX } from '../../constants'
import { cleanUrl, fsPathFromId, normalizePath, injectQuery } from '../../utils'
import type { ModuleGraph } from '../moduleGraph'
export function createDevHtmlTransformFn(
server: ViteDevServer
): (url: string, html: string, originalUrl: string) => Promise<string> {
const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins)
return (url: string, html: string, originalUrl: string): Promise<string> => {
return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], {
path: url,
filename: getHtmlFilename(url, server),
server,
originalUrl
})
}
}
function getHtmlFilename(url: string, server: ViteDevServer) {
if (url.startsWith(FS_PREFIX)) {
return decodeURIComponent(fsPathFromId(url))
} else {
return decodeURIComponent(path.join(server.config.root, url.slice(1)))
}
}
const startsWithSingleSlashRE = /^\/(?!\/)/
const processNodeUrl = (
node: AttributeNode,
s: MagicString,
config: ResolvedConfig,
htmlPath: string,
originalUrl?: string,
moduleGraph?: ModuleGraph
) => {
let url = node.value?.content || ''
if (moduleGraph) {
const mod = moduleGraph.urlToModuleMap.get(url)
if (mod && mod.lastHMRTimestamp > 0) {
url = injectQuery(url, `t=${mod.lastHMRTimestamp}`)
}
}
if (startsWithSingleSlashRE.test(url)) {
// prefix with base
s.overwrite(
node.value!.loc.start.offset,
node.value!.loc.end.offset,
`"${config.base + url.slice(1)}"`
)
} else if (
url.startsWith('.') &&
originalUrl &&
originalUrl !== '/' &&
htmlPath === '/index.html'
) {
// #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
// path will add `/a/` prefix, it will caused 404.
// rewrite before `./index.js` -> `localhost:3000/a/index.js`.
// rewrite after `../index.js` -> `localhost:3000/index.js`.
s.overwrite(
node.value!.loc.start.offset,
node.value!.loc.end.offset,
`"${path.posix.join(
path.posix.relative(originalUrl, '/'),
url.slice(1)
)}"`
)
}
}
const devHtmlHook: IndexHtmlTransformHook = async (
html,
{ path: htmlPath, server, originalUrl }
) => {
const { config, moduleGraph } = server!
const base = config.base || '/'
const s = new MagicString(html)
let inlineModuleIndex = -1
const filePath = cleanUrl(htmlPath)
const addInlineModule = (node: ElementNode, ext: 'js' | 'css') => {
inlineModuleIndex++
const url = filePath.replace(normalizePath(config.root), '')
const contents = node.children
.map((child: any) => child.content || '')
.join('')
// add HTML Proxy to Map
addToHTMLProxyCache(config, url, inlineModuleIndex, contents)
// inline js module. convert to src="proxy"
const modulePath = `${
config.base + htmlPath.slice(1)
}?html-proxy&index=${inlineModuleIndex}.${ext}`
// invalidate the module so the newly cached contents will be served
const module = server?.moduleGraph.getModuleById(modulePath)
if (module) {
server?.moduleGraph.invalidateModule(module)
}
s.overwrite(
node.loc.start.offset,
node.loc.end.offset,
`<script type="module" src="${modulePath}"></script>`
)
}
await traverseHtml(html, htmlPath, (node) => {
if (node.type !== NodeTypes.ELEMENT) {
return
}
// script tags
if (node.tag === 'script') {
const { src, isModule } = getScriptInfo(node)
if (src) {
processNodeUrl(src, s, config, htmlPath, originalUrl, moduleGraph)
} else if (isModule) {
addInlineModule(node, 'js')
}
}
if (node.tag === 'style' && node.children.length) {
addInlineModule(node, 'css')
}
// elements with [href/src] attrs
const assetAttrs = assetAttrsConfig[node.tag]
if (assetAttrs) {
for (const p of node.props) {
if (
p.type === NodeTypes.ATTRIBUTE &&
p.value &&
assetAttrs.includes(p.name)
) {
processNodeUrl(p, s, config, htmlPath, originalUrl)
}
}
}
})
html = s.toString()
return {
html,
tags: [
{
tag: 'script',
attrs: {
type: 'module',
src: path.posix.join(base, CLIENT_PUBLIC_PATH)
},
injectTo: 'head-prepend'
}
]
}
}
export function indexHtmlMiddleware(
server: ViteDevServer
): Connect.NextHandleFunction {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return async function viteIndexHtmlMiddleware(req, res, next) {
if (res.writableEnded) {
return next()
}
const url = req.url && cleanUrl(req.url)
// spa-fallback always redirects to /index.html
if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {
const filename = getHtmlFilename(url, server)
if (fs.existsSync(filename)) {
try {
let html = fs.readFileSync(filename, 'utf-8')
html = await server.transformIndexHtml(url, html, req.originalUrl)
return send(req, res, html, 'html', {
headers: server.config.server.headers
})
} catch (e) {
return next(e)
}
}
}
next()
}
}