-
Notifications
You must be signed in to change notification settings - Fork 7
/
multiPagePlugin.ts
249 lines (233 loc) · 7.9 KB
/
multiPagePlugin.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import type { Plugin, ResolvedConfig, UserConfig, Connect } from 'vite'
import type { Data } from 'ejs'
import type { IncomingMessage } from 'http'
import type { Options, InjectOptions, Pages, Rewrite } from './types'
import { relative, resolve, basename, posix } from 'path'
import { render } from 'ejs'
import { loadEnv, normalizePath as _normalizePath } from 'vite'
import history from 'connect-history-api-fallback'
import { processTags } from './htmlFixPlugin'
const VITE_PLUGIN_NAME = 'vite-plugin-mpa-plus'
const DEFAULT_TEMPLATE = 'index.html'
const INJECT_ENTRY = /<\/body>/
const IS_INDEX = /^\/index$|^\/$/
const SKIPPED_EXTENSIONS = [
'.mjs',
'.js',
'.ts',
'.jsx',
'.tsx',
'.json',
'.vue'
]
const SKIPPED_EXTENSIONS_REGEX = new RegExp(`\\.(${SKIPPED_EXTENSIONS.join('|').replace(/\./g, '')})$`)
function slash(p: string): string {
return p.replace(/\\/g, '/')
}
function genHistoryApiFallbackRewrites(base: string, pages: Pages = {}) {
const multiPageRewrites = Object
.keys(pages)
.sort((a, b) => b.length - a.length)
.map(name => ({
from: new RegExp(`^/${name}`),
to: posix.join(base, pages[name].template || `${name}.html`)
}))
return [
...multiPageRewrites,
{ from: /^\/$/, to: posix.join(base, 'index.html') }
]
}
// this is a try
function evaluateRewriteTo(req: Partial<IncomingMessage>, from: RegExp | undefined, to: any) {
const url = req.url || ''
const match = url.match(from || /(?:)/)
if (typeof to === 'string') {
return to
}
if (typeof to === 'function') {
return to({
url,
match,
req
})
}
throw new Error('Rewrite rule can only be of type string or function.')
}
// Process the normalized path again
export function normalizePath(id: string) {
const fsPath = slash(relative(process.cwd(), _normalizePath(`${id}`)))
if (fsPath.startsWith('/') || fsPath.startsWith('../')) {
return fsPath
}
return `/${fsPath}`
}
// create input
export function createInput(options: Options, viteConfig: UserConfig | ResolvedConfig) {
let isMpa = false
const { pages = {}, template = DEFAULT_TEMPLATE } = options
const { root } = viteConfig
const input = Object.keys(pages).reduce<Record<string, string>>((result, page) => {
isMpa = true
const { template } = pages[page]
result[page] = resolve(root || process.cwd(), template)
return result
}, {})
if (!isMpa) {
const file = basename(template)
const key = file.replace(/\.html/, '')
return {
[key]: resolve(root || process.cwd(), template),
}
}
return {
...input,
...(viteConfig.build?.rollupOptions?.input as Record<string, string> ?? {})
}
}
// create page
export function createPage(
options: Options,
fsPath: string
) {
let page
const {
pages = {},
entry, template, inject
} = options
const mpaNames = Object.keys(pages)
if (mpaNames.length) {
const name = mpaNames.filter(name => resolve(`/${pages[name].template}`) === resolve(`/${fsPath}`))?.[0]
page = pages[name]
} else {
page = {
entry,
filename: 'index.html',
template,
inject
}
}
return page
}
// Find the page according to ' rewrites.from '
// this is a try
export function tryFindPage(forgeReq: Partial<IncomingMessage>, rewrites: Rewrite[], pages: Pages = {}) {
const { url } = forgeReq
if (SKIPPED_EXTENSIONS_REGEX.test(url || '')) return
const isIndex = url?.match(IS_INDEX)
const rewrite = rewrites.find(item => {
if (isIndex) {
return '/index'.match(item.from) || '/'.match(item.from) // Compatible with /^\/index$/ /^\/$/
}
return url?.match(item.from)
})
if (!rewrite) return
const to = evaluateRewriteTo(forgeReq, rewrite.from, rewrite.to)
const page = Object.values(pages).find(page => _normalizePath(`/${page.filename}`) === _normalizePath(`/${to}`))
return page
}
export async function renderHtml(
html: string,
pageOptions: {
inject: InjectOptions
viteConfig: ResolvedConfig
env: Record<string, string>
entry?: string
},
) {
const { inject, viteConfig, env, entry } = pageOptions
const { data, ejsOptions } = inject
const ejsData: Data = {
...(viteConfig?.env ?? {}),
...(viteConfig?.define ?? {}),
...(env || {}),
...data,
}
let result = await render(html, ejsData, ejsOptions)
if (entry) {
result = result.replace(
INJECT_ENTRY,
`<script type="module" src="${normalizePath(`${entry}`)}"></script>\n</body>`,
)
}
return result
}
export function createMpaPlugin(options: Options): Plugin {
let viteConfig: ResolvedConfig
let env: Record<string, string> = {}
let rewrites: Rewrite[] = []
return {
name: VITE_PLUGIN_NAME,
enforce: 'pre',
config(config) {
const input = createInput(options, config)
return {
build: {
rollupOptions: {
input,
},
},
}
},
configResolved(config) {
env = loadEnv(config.mode, config.root)
viteConfig = config
},
configureServer(server) {
const { historyApiFallback, pages = {} } = options
const { base } = viteConfig
if (historyApiFallback?.rewrites) {
rewrites = Object.values(pages).map(page => ({
from: new RegExp(`^/${page.filename}`),
to: posix.join(base, page.template)
}))
rewrites = [
...rewrites,
...historyApiFallback.rewrites
]
Reflect.deleteProperty(historyApiFallback, 'rewrites')
} else {
rewrites = genHistoryApiFallbackRewrites(base, pages)
}
server.middlewares.use(async (req, res, next) => {
const page = tryFindPage(req, rewrites, pages)
if (page) {
// const fsPath = resolve(viteConfig.root || process.cwd(), page.template)
// let content = readFileSync(fsPath, { encoding: 'utf-8' })
// content = await server.transformIndexHtml(_normalizePath(`/${page?.template}`), content, req.originalUrl)
// res.end(content)
req.url = _normalizePath(`/${page.template}`)
}
next()
})
server.middlewares.use(history({
disableDotRule: undefined,
htmlAcceptHeaders: [
'text/html',
'application/xhtml+xml'
],
rewrites,
...historyApiFallback
}) as Connect.NextHandleFunction)
},
transformIndexHtml: {
order: 'pre',
async handler(html, ctx) {
const url = ctx.filename
const { base, root } = viteConfig // process.cwd() > vite.root, The default root is process.cwd(), Fixing edge problems.
const excludeBaseUrl = url.replace(base, '/')
const template = relative(root, excludeBaseUrl)
const page = tryFindPage({ url: ctx.originalUrl }, rewrites, options.pages) ?? createPage(options, template)
const _html = await renderHtml(html, {
entry: page?.entry,
inject: page?.inject ?? {},
viteConfig,
env
})
return {
html: _html,
tags: processTags(page?.inject?.tags ?? []) ?? []
}
},
}
}
}