-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
plugin.ts
244 lines (222 loc) · 6.56 KB
/
plugin.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
import path from 'path'
import { mergeConfig, Plugin, ResolvedConfig } from 'vite'
import { SiteConfig, resolveSiteData } from './config'
import {
createMarkdownToVueRenderFn,
MarkdownCompileResult
} from './markdownToVue'
import { APP_PATH, SITE_DATA_REQUEST_PATH } from './alias'
import createVuePlugin from '@vitejs/plugin-vue'
import { slash } from './utils/slash'
import { OutputAsset, OutputChunk } from 'rollup'
const hashRE = /\.(\w+)\.js$/
const staticInjectMarkerRE =
/\b(const _hoisted_\d+ = \/\*#__PURE__\*\/createStaticVNode)\("(.*)", (\d+)\)/g
const staticStripRE = /__VP_STATIC_START__.*?__VP_STATIC_END__/g
const staticRestoreRE = /__VP_STATIC_(START|END)__/g
const isPageChunk = (
chunk: OutputAsset | OutputChunk
): chunk is OutputChunk & { facadeModuleId: string } =>
!!(
chunk.type === 'chunk' &&
chunk.isEntry &&
chunk.facadeModuleId &&
chunk.facadeModuleId.endsWith('.md')
)
export function createVitePressPlugin(
root: string,
{
srcDir,
configPath,
alias,
markdown,
site,
vue: userVuePluginOptions,
vite: userViteConfig,
pages
}: SiteConfig,
ssr = false,
pageToHashMap?: Record<string, string>
): Plugin[] {
let markdownToVue: (
src: string,
file: string,
publicDir: string
) => MarkdownCompileResult
const vuePlugin = createVuePlugin({
include: [/\.vue$/, /\.md$/],
...userVuePluginOptions
})
let siteData = site
let hasDeadLinks = false
let config: ResolvedConfig
const vitePressPlugin: Plugin = {
name: 'vitepress',
configResolved(resolvedConfig) {
config = resolvedConfig
markdownToVue = createMarkdownToVueRenderFn(
srcDir,
markdown,
pages,
config.define,
config.command === 'build'
)
},
config() {
const baseConfig = {
resolve: {
alias
},
define: {
__CARBON__: !!site.themeConfig.carbonAds?.carbon,
__BSA__: !!site.themeConfig.carbonAds?.custom,
__ALGOLIA__: !!site.themeConfig.algolia
},
optimizeDeps: {
// force include vue to avoid duplicated copies when linked + optimized
include: ['vue'],
exclude: ['@docsearch/js']
}
}
return userViteConfig
? mergeConfig(userViteConfig, baseConfig)
: baseConfig
},
resolveId(id) {
if (id === SITE_DATA_REQUEST_PATH) {
return SITE_DATA_REQUEST_PATH
}
},
load(id) {
if (id === SITE_DATA_REQUEST_PATH) {
return `export default ${JSON.stringify(JSON.stringify(siteData))}`
}
},
transform(code, id) {
if (id.endsWith('.md')) {
// transform .md files into vueSrc so plugin-vue can handle it
const { vueSrc, deadLinks } = markdownToVue(code, id, config.publicDir)
if (deadLinks.length) {
hasDeadLinks = true
}
return vueSrc
}
},
renderStart() {
if (hasDeadLinks) {
throw new Error(`One or more pages contain dead links.`)
}
},
configureServer(server) {
server.watcher.add(configPath)
// serve our index.html after vite history fallback
return () => {
server.middlewares.use((req, res, next) => {
if (req.url!.endsWith('.html')) {
res.statusCode = 200
res.end(`
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="">
</head>
<body>
<div id="app"></div>
<script type="module" src="/@fs/${APP_PATH}/index.js"></script>
</body>
</html>`)
return
}
next()
})
}
},
renderChunk(code, chunk) {
if (!ssr && isPageChunk(chunk as OutputChunk)) {
// For each page chunk, inject marker for start/end of static strings.
// we do this here because in generateBundle the chunks would have been
// minified and we won't be able to safely locate the strings.
// Using a regexp relies on specific output from Vue compiler core,
// which is a reasonable trade-off considering the massive perf win over
// a full AST parse.
code = code.replace(
staticInjectMarkerRE,
'$1("__VP_STATIC_START__$2__VP_STATIC_END__", $3)'
)
return code
}
return null
},
generateBundle(_options, bundle) {
if (ssr) {
// ssr build:
// delete all asset chunks
for (const name in bundle) {
if (bundle[name].type === 'asset') {
delete bundle[name]
}
}
} else {
// client build:
// for each .md entry chunk, adjust its name to its correct path.
for (const name in bundle) {
const chunk = bundle[name]
if (isPageChunk(chunk)) {
// record page -> hash relations
const hash = chunk.fileName.match(hashRE)![1]
pageToHashMap![chunk.name.toLowerCase()] = hash
// inject another chunk with the content stripped
bundle[name + '-lean'] = {
...chunk,
fileName: chunk.fileName.replace(/\.js$/, '.lean.js'),
code: chunk.code.replace(staticStripRE, ``)
}
// remove static markers from original code
chunk.code = chunk.code.replace(staticRestoreRE, '')
}
}
}
},
async handleHotUpdate(ctx) {
// handle config hmr
const { file, read, server } = ctx
if (file === configPath) {
const newData = await resolveSiteData(root)
if (newData.base !== siteData.base) {
console.warn(
`[vitepress]: config.base has changed. Please restart the dev server.`
)
}
siteData = newData
return [server.moduleGraph.getModuleById(SITE_DATA_REQUEST_PATH)!]
}
// hot reload .md files as .vue files
if (file.endsWith('.md')) {
const content = await read()
const { pageData, vueSrc } = markdownToVue(
content,
file,
config.publicDir
)
// notify the client to update page data
server.ws.send({
type: 'custom',
event: 'vitepress:pageData',
data: {
path: `/${slash(path.relative(srcDir, file))}`,
pageData
}
})
// reload the content component
return vuePlugin.handleHotUpdate!({
...ctx,
read: () => vueSrc
})
}
}
}
return [vitePressPlugin, vuePlugin]
}