/
config.ts
381 lines (344 loc) · 10.3 KB
/
config.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import path from 'path'
import fs from 'fs-extra'
import c from 'picocolors'
import fg from 'fast-glob'
import {
normalizePath,
UserConfig as ViteConfig,
mergeConfig as mergeViteConfig,
loadConfigFromFile
} from 'vite'
import { Options as VuePluginOptions } from '@vitejs/plugin-vue'
import {
SiteData,
HeadConfig,
LocaleConfig,
DefaultTheme,
APPEARANCE_KEY,
createLangDictionary,
CleanUrlsMode,
PageData,
Awaitable
} from './shared'
import { DEFAULT_THEME_PATH } from './alias'
import { MarkdownOptions } from './markdown/markdown'
import _debug from 'debug'
export { resolveSiteDataByRoute } from './shared'
const debug = _debug('vitepress:config')
export interface UserConfig<ThemeConfig = any> {
extends?: RawConfigExports<ThemeConfig>
base?: string
lang?: string
title?: string
titleTemplate?: string | boolean
description?: string
head?: HeadConfig[]
appearance?: boolean | 'dark'
themeConfig?: ThemeConfig
locales?: Record<string, LocaleConfig>
markdown?: MarkdownOptions
lastUpdated?: boolean
/**
* Options to pass on to `@vitejs/plugin-vue`
*/
vue?: VuePluginOptions
/**
* Vite config
*/
vite?: ViteConfig
srcDir?: string
srcExclude?: string[]
outDir?: string
shouldPreload?: (link: string, page: string) => boolean
/**
* Configure the scroll offset when the theme has a sticky header.
* Can be a number or a selector element to get the offset from.
*/
scrollOffset?: number | string
/**
* Enable MPA / zero-JS mode.
* @experimental
*/
mpa?: boolean
/**
* Don't fail builds due to dead links.
*
* @default false
*/
ignoreDeadLinks?: boolean
/**
* @experimental
* Remove '.html' from URLs and generate clean directory structure.
*
* Available Modes:
* - `disabled`: generates `/foo.html` for every `/foo.md` and shows `/foo.html` in browser
* - `without-subfolders`: generates `/foo.html` for every `/foo.md` but shows `/foo` in browser
* - `with-subfolders`: generates `/foo/index.html` for every `/foo.md` and shows `/foo` in browser
*
* @default 'disabled'
*/
cleanUrls?: CleanUrlsMode
/**
* Use web fonts instead of emitting font files to dist.
* The used theme should import a file named `fonts.(s)css` for this to work.
* If you are a theme author, to support this, place your web font import
* between `webfont-marker-begin` and `webfont-marker-end` comments.
*
* @default true in webcontainers, else false
*/
useWebFonts?: boolean
/**
* Build end hook: called when SSG finish.
* @param siteConfig The resolved configuration.
*/
buildEnd?: (siteConfig: SiteConfig) => Awaitable<void>
/**
* Head transform hook: runs before writing HTML to dist.
*
* This build hook will allow you to modify the head adding new entries that cannot be statically added.
*/
transformHead?: (ctx: TransformContext) => Awaitable<HeadConfig[]>
/**
* HTML transform hook: runs before writing HTML to dist.
*/
transformHtml?: (
code: string,
id: string,
ctx: TransformContext
) => Awaitable<string | void>
/**
* PageData transform hook: runs when rendering markdown to vue
*/
transformPageData?: (
pageData: PageData
) => Awaitable<Partial<PageData> | { [key: string]: any } | void>
}
export interface TransformContext {
siteConfig: SiteConfig
siteData: SiteData
pageData: PageData
title: string
description: string
head: HeadConfig[]
content: string
}
export type RawConfigExports<ThemeConfig = any> =
| Awaitable<UserConfig<ThemeConfig>>
| (() => Awaitable<UserConfig<ThemeConfig>>)
export interface SiteConfig<ThemeConfig = any>
extends Pick<
UserConfig,
| 'markdown'
| 'vue'
| 'vite'
| 'shouldPreload'
| 'mpa'
| 'lastUpdated'
| 'ignoreDeadLinks'
| 'cleanUrls'
| 'useWebFonts'
| 'buildEnd'
| 'transformHead'
| 'transformHtml'
| 'transformPageData'
> {
root: string
srcDir: string
site: SiteData<ThemeConfig>
configPath: string | undefined
configDeps: string[]
themeDir: string
outDir: string
tempDir: string
pages: string[]
}
const resolve = (root: string, file: string) =>
normalizePath(path.resolve(root, `.vitepress`, file))
/**
* Type config helper
*/
export function defineConfig(config: UserConfig<DefaultTheme.Config>) {
return config
}
/**
* Type config helper for custom theme config
*/
export function defineConfigWithTheme<ThemeConfig>(
config: UserConfig<ThemeConfig>
) {
return config
}
export async function resolveConfig(
root: string = process.cwd(),
command: 'serve' | 'build' = 'serve',
mode = 'development'
): Promise<SiteConfig> {
const [userConfig, configPath, configDeps] = await resolveUserConfig(
root,
command,
mode
)
const site = await resolveSiteData(root, userConfig)
const srcDir = path.resolve(root, userConfig.srcDir || '.')
const outDir = userConfig.outDir
? path.resolve(root, userConfig.outDir)
: resolve(root, 'dist')
// resolve theme path
const userThemeDir = resolve(root, 'theme')
const themeDir = (await fs.pathExists(userThemeDir))
? userThemeDir
: DEFAULT_THEME_PATH
// Important: fast-glob doesn't guarantee order of the returned files.
// We must sort the pages so the input list to rollup is stable across
// builds - otherwise different input order could result in different exports
// order in shared chunks which in turns invalidates the hash of every chunk!
// JavaScript built-in sort() is mandated to be stable as of ES2019 and
// supported in Node 12+, which is required by Vite.
const pages = (
await fg(['**.md'], {
cwd: srcDir,
ignore: ['**/node_modules', ...(userConfig.srcExclude || [])]
})
).sort()
const config: SiteConfig = {
root,
srcDir,
site,
themeDir,
pages,
configPath,
configDeps,
outDir,
tempDir: resolve(root, '.temp'),
markdown: userConfig.markdown,
lastUpdated: userConfig.lastUpdated,
vue: userConfig.vue,
vite: userConfig.vite,
shouldPreload: userConfig.shouldPreload,
mpa: !!userConfig.mpa,
ignoreDeadLinks: userConfig.ignoreDeadLinks,
cleanUrls: userConfig.cleanUrls || 'disabled',
useWebFonts:
userConfig.useWebFonts ??
typeof process.versions.webcontainer === 'string',
buildEnd: userConfig.buildEnd,
transformHead: userConfig.transformHead,
transformHtml: userConfig.transformHtml,
transformPageData: userConfig.transformPageData
}
return config
}
const supportedConfigExtensions = ['js', 'ts', 'cjs', 'mjs', 'cts', 'mts']
async function resolveUserConfig(
root: string,
command: 'serve' | 'build',
mode: string
): Promise<[UserConfig, string | undefined, string[]]> {
// load user config
const configPath = supportedConfigExtensions
.map((ext) => resolve(root, `config.${ext}`))
.find(fs.pathExistsSync)
let userConfig: RawConfigExports = {}
let configDeps: string[] = []
if (!configPath) {
debug(`no config file found.`)
} else {
const configExports = await loadConfigFromFile(
{ command, mode },
configPath,
root
)
if (configExports) {
userConfig = configExports.config
configDeps = configExports.dependencies.map((file) =>
normalizePath(path.resolve(file))
)
}
debug(`loaded config at ${c.yellow(configPath)}`)
}
return [await resolveConfigExtends(userConfig), configPath, configDeps]
}
async function resolveConfigExtends(
config: RawConfigExports
): Promise<UserConfig> {
const resolved = await (typeof config === 'function' ? config() : config)
if (resolved.extends) {
const base = await resolveConfigExtends(resolved.extends)
return mergeConfig(base, resolved)
}
return resolved
}
function mergeConfig(a: UserConfig, b: UserConfig, isRoot = true) {
const merged: Record<string, any> = { ...a }
for (const key in b) {
const value = b[key as keyof UserConfig]
if (value == null) {
continue
}
const existing = merged[key]
if (Array.isArray(existing) && Array.isArray(value)) {
merged[key] = [...existing, ...value]
continue
}
if (isObject(existing) && isObject(value)) {
if (isRoot && key === 'vite') {
merged[key] = mergeViteConfig(existing, value)
} else {
merged[key] = mergeConfig(existing, value, false)
}
continue
}
merged[key] = value
}
return merged
}
function isObject(value: unknown): value is Record<string, any> {
return Object.prototype.toString.call(value) === '[object Object]'
}
export async function resolveSiteData(
root: string,
userConfig?: UserConfig,
command: 'serve' | 'build' = 'serve',
mode = 'development'
): Promise<SiteData> {
userConfig = userConfig || (await resolveUserConfig(root, command, mode))[0]
return {
lang: userConfig.lang || 'en-US',
title: userConfig.title || 'VitePress',
titleTemplate: userConfig.titleTemplate,
description: userConfig.description || 'A VitePress site',
base: userConfig.base ? userConfig.base.replace(/([^/])$/, '$1/') : '/',
head: resolveSiteDataHead(userConfig),
appearance: userConfig.appearance ?? true,
themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {},
langs: createLangDictionary(userConfig),
scrollOffset: userConfig.scrollOffset || 90,
cleanUrls: userConfig.cleanUrls || 'disabled'
}
}
function resolveSiteDataHead(userConfig?: UserConfig): HeadConfig[] {
const head = userConfig?.head ?? []
// add inline script to apply dark mode, if user enables the feature.
// this is required to prevent "flash" on initial page load.
if (userConfig?.appearance ?? true) {
// if appearance mode set to light or dark, default to the defined mode
// in case the user didn't specify a preference - otherwise, default to auto
const fallbackPreference =
userConfig?.appearance !== true ? userConfig?.appearance ?? '' : 'auto'
head.push([
'script',
{ id: 'check-dark-light' },
`
;(() => {
const preference = localStorage.getItem('${APPEARANCE_KEY}') || '${fallbackPreference}'
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
if (!preference || preference === 'auto' ? prefersDark : preference === 'dark') {
document.documentElement.classList.add('dark')
}
})()
`
])
}
return head
}