Merge branch 'vuejs:main' into doc-zh

pull/2249/head
vanchKong 2 years ago committed by GitHub
commit 2d8aafe61d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,2 +1,2 @@
shell-emulator=true
resolution-mode=highest
auto-install-peers=false

@ -1,3 +1,44 @@
# [1.0.0-rc.29](https://github.com/vuejs/vitepress/compare/v1.0.0-rc.28...v1.0.0-rc.29) (2023-11-19)
### Bug Fixes
- **client:** regression - router not working without .html present ([d63cb86](https://github.com/vuejs/vitepress/commit/d63cb867b14ba49c8333ad0d69d33874e2ece6c6)), closes [#3225](https://github.com/vuejs/vitepress/issues/3225)
# [1.0.0-rc.28](https://github.com/vuejs/vitepress/compare/v1.0.0-rc.27...v1.0.0-rc.28) (2023-11-18)
### Bug Fixes
- **ally:** clear up confusion with the title of theme switch ([#3215](https://github.com/vuejs/vitepress/issues/3215)) ([6761036](https://github.com/vuejs/vitepress/commit/67610363bcb354d33327e6b5c3c2d916ed025ffc))
- **build:** support nested assetsDir ([02161d0](https://github.com/vuejs/vitepress/commit/02161d0f797cfa36d715119e8c7618770b1a6761))
- wrong recognition of non-html extension leads to route error ([#3218](https://github.com/vuejs/vitepress/issues/3218)) ([c4abc95](https://github.com/vuejs/vitepress/commit/c4abc950af7061611e3b5eff93e767706bd12396))
### Features
- **build:** html head meta generator ([#3219](https://github.com/vuejs/vitepress/issues/3219)) ([672e494](https://github.com/vuejs/vitepress/commit/672e4946ac3c24f3fc79469534e66cfaf6f23e67))
- **client:** allow disabling link auto-prefetching ([#3220](https://github.com/vuejs/vitepress/issues/3220)) ([563dc89](https://github.com/vuejs/vitepress/commit/563dc899757e58d2261bcb31081283eb395fab0b))
# [1.0.0-rc.27](https://github.com/vuejs/vitepress/compare/v1.0.0-rc.26...v1.0.0-rc.27) (2023-11-17)
### Bug Fixes
- CSS missing after build ([#3217](https://github.com/vuejs/vitepress/issues/3217)) ([da73b58](https://github.com/vuejs/vitepress/commit/da73b58c795a65a09d028e0ca6acefa1170d3d5b)), closes [#3216](https://github.com/vuejs/vitepress/issues/3216)
# [1.0.0-rc.26](https://github.com/vuejs/vitepress/compare/v1.0.0-rc.25...v1.0.0-rc.26) (2023-11-16)
### Bug Fixes
- "VPNavScreenMenuGroup" component HTML not supported ([#3148](https://github.com/vuejs/vitepress/issues/3148)) ([237ad85](https://github.com/vuejs/vitepress/commit/237ad859a982f3fa55f7bba0f98ca94707108618))
- **build:** remove frontmatter in md file inclusion ([dbbffa2](https://github.com/vuejs/vitepress/commit/dbbffa2487cd1f9899916baa166591248fb24334)), closes [#3195](https://github.com/vuejs/vitepress/issues/3195)
- style links in footer ([#3178](https://github.com/vuejs/vitepress/issues/3178)) ([a482611](https://github.com/vuejs/vitepress/commit/a482611d17197a0b7afc403891cd95f344e7a55f))
### Features
- switch to vite 5 and bump deps ([#3200](https://github.com/vuejs/vitepress/issues/3200)) ([d2238ee](https://github.com/vuejs/vitepress/commit/d2238eedb7c0c81b2d9f425e6f70f7019ad6a482))
### BREAKING CHANGES
- VitePress now runs on Vite 5. Please refer https://vitejs.dev/guide/migration for breaking changes and migration guide if you're relying on some Vite-specific things.
# [1.0.0-rc.25](https://github.com/vuejs/vitepress/compare/v1.0.0-rc.24...v1.0.0-rc.25) (2023-11-05)
### Bug Fixes

@ -4,8 +4,8 @@ exports[`render correct content > main content 1`] = `
[
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \\"de Finibus Bonorum et Malorum\\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \\"Lorem ipsum dolor sit amet..\\", comes from a line in section 1.10.32.",
"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \\"de Finibus Bonorum et Malorum\\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.",
"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).",
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.",
]

@ -7,34 +7,34 @@ describe('static data file support in vite 3', () => {
expect(await page.textContent('pre#basic')).toMatchInlineSnapshot(`
"[
{
\\"foo\\": true
"foo": true
},
{
\\"bar\\": true
"bar": true
}
]"
`)
expect(await page.textContent('pre#content')).toMatchInlineSnapshot(`
"[
{
\\"src\\": \\"---\\\\ntitle: bar\\\\n---\\\\n\\\\nHello\\\\n\\\\n---\\\\n\\\\nworld\\\\n\\",
\\"html\\": \\"<p>Hello</p>\\\\n<hr>\\\\n<p>world</p>\\\\n\\",
\\"frontmatter\\": {
\\"title\\": \\"bar\\"
"src": "---\\ntitle: bar\\n---\\n\\nHello\\n\\n---\\n\\nworld\\n",
"html": "<p>Hello</p>\\n<hr>\\n<p>world</p>\\n",
"frontmatter": {
"title": "bar"
},
\\"excerpt\\": \\"<p>Hello</p>\\\\n\\",
\\"url\\": \\"/data-loading/content/bar.html\\",
\\"transformed\\": true
"excerpt": "<p>Hello</p>\\n",
"url": "/data-loading/content/bar.html",
"transformed": true
},
{
\\"src\\": \\"---\\\\ntitle: foo\\\\n---\\\\n\\\\nHello\\\\n\\\\n---\\\\n\\\\nworld\\\\n\\",
\\"html\\": \\"<p>Hello</p>\\\\n<hr>\\\\n<p>world</p>\\\\n\\",
\\"frontmatter\\": {
\\"title\\": \\"foo\\"
"src": "---\\ntitle: foo\\n---\\n\\nHello\\n\\n---\\n\\nworld\\n",
"html": "<p>Hello</p>\\n<hr>\\n<p>world</p>\\n",
"frontmatter": {
"title": "foo"
},
\\"excerpt\\": \\"<p>Hello</p>\\\\n\\",
\\"url\\": \\"/data-loading/content/foo.html\\",
\\"transformed\\": true
"excerpt": "<p>Hello</p>\\n",
"url": "/data-loading/content/foo.html",
"transformed": true
}
]"
`)

@ -1,10 +1,13 @@
import fs from 'fs-extra'
import getPort from 'get-port'
import { nanoid } from 'nanoid'
import path from 'path'
import { chromium } from 'playwright-chromium'
import { fileURLToPath, URL } from 'url'
import { createServer, scaffold, ScaffoldThemeType } from 'vitepress'
const root = fileURLToPath(new URL('./.temp', import.meta.url))
const tempDir = fileURLToPath(new URL('./.temp', import.meta.url))
const getTempRoot = () => path.join(tempDir, nanoid())
const browser = await chromium.launch({
headless: !process.env.DEBUG,
@ -30,9 +33,11 @@ const variations = themes.flatMap((theme) =>
afterAll(async () => {
await page.close()
await browser.close()
await fs.remove(tempDir)
})
test.each(variations)('init %s', async (_, { theme, useTs }) => {
const root = getTempRoot()
await fs.remove(root)
scaffold({ root, theme, useTs, injectNpmScripts: false })
@ -62,7 +67,6 @@ test.each(variations)('init %s', async (_, { theme, useTs }) => {
// teardown
} finally {
await fs.remove(root)
await server.close()
}
})

@ -50,7 +50,7 @@ describe('node/markdown/plugins/snippet', () => {
)
).toMatchInlineSnapshot(`
"fn main() {
println!(\\"Hello\\");
println!("Hello");
}"
`)
})

@ -230,7 +230,7 @@ export { data }
export default defineLoader({
// type checked loader options
glob: ['...'],
watch: ['...'],
async load(): Promise<Data> {
// ...
}

@ -360,7 +360,7 @@ export default {
- Type: `string`
- Default: `assets`
The directory for assets files. See also: [assetsDir](https://vitejs.dev/config/build-options.html#build-assetsdir).
Specify the directory to nest generated assets under. The path should be inside [`outDir`](#outdir) and is resolved relative to it.
```ts
export default {

@ -1,9 +1,9 @@
{
"name": "vitepress",
"version": "1.0.0-rc.25",
"version": "1.0.0-rc.29",
"description": "Vite & Vue powered static site generator",
"type": "module",
"packageManager": "pnpm@8.9.2",
"packageManager": "pnpm@8.10.5",
"main": "dist/node/index.js",
"types": "types/index.d.ts",
"exports": {
@ -92,17 +92,18 @@
"dependencies": {
"@docsearch/css": "^3.5.2",
"@docsearch/js": "^3.5.2",
"@types/markdown-it": "^13.0.4",
"@vitejs/plugin-vue": "4.3.1",
"@types/markdown-it": "^13.0.6",
"@vitejs/plugin-vue": "^4.5.0",
"@vue/devtools-api": "^6.5.1",
"@vueuse/core": "^10.5.0",
"@vueuse/integrations": "^10.5.0",
"@vueuse/core": "^10.6.1",
"@vueuse/integrations": "^10.6.1",
"focus-trap": "^7.5.4",
"mark.js": "8.11.1",
"minisearch": "^6.1.0",
"minisearch": "^6.2.0",
"mrmime": "^1.0.1",
"shiki": "^0.14.5",
"vite": "^4.5.0",
"vue": "^3.3.6"
"vite": "^5.0.0",
"vue": "^3.3.8"
},
"peerDependencies": {
"markdown-it-mathjax3": "^4.3.2",
@ -129,23 +130,23 @@
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.0.1",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^5.0.4",
"@types/compression": "^1.7.4",
"@types/cross-spawn": "^6.0.4",
"@types/debug": "^4.1.10",
"@types/escape-html": "^1.0.3",
"@types/fs-extra": "^11.0.3",
"@types/lodash.template": "^4.5.2",
"@types/mark.js": "^8.11.10",
"@types/markdown-it-attrs": "^4.1.2",
"@types/markdown-it-container": "^2.0.8",
"@types/markdown-it-emoji": "^2.0.3",
"@types/micromatch": "^4.0.4",
"@types/minimist": "^1.2.4",
"@types/node": "^20.8.7",
"@types/postcss-prefix-selector": "^1.16.2",
"@types/prompts": "^2.4.7",
"@vue/shared": "^3.3.6",
"@rollup/plugin-replace": "^5.0.5",
"@types/compression": "^1.7.5",
"@types/cross-spawn": "^6.0.5",
"@types/debug": "^4.1.12",
"@types/escape-html": "^1.0.4",
"@types/fs-extra": "^11.0.4",
"@types/lodash.template": "^4.5.3",
"@types/mark.js": "^8.11.11",
"@types/markdown-it-attrs": "^4.1.3",
"@types/markdown-it-container": "^2.0.9",
"@types/markdown-it-emoji": "^2.0.4",
"@types/micromatch": "^4.0.5",
"@types/minimist": "^1.2.5",
"@types/node": "^20.9.1",
"@types/postcss-prefix-selector": "^1.16.3",
"@types/prompts": "^2.4.8",
"@vue/shared": "^3.3.8",
"chokidar": "^3.5.3",
"compression": "^1.7.4",
"conventional-changelog-cli": "^4.1.0",
@ -154,13 +155,13 @@
"esbuild": "^0.19.5",
"escape-html": "^1.0.3",
"execa": "^8.0.1",
"fast-glob": "^3.3.1",
"fast-glob": "^3.3.2",
"fs-extra": "^11.1.1",
"get-port": "^7.0.0",
"gray-matter": "^4.0.3",
"lint-staged": "^15.0.2",
"lint-staged": "^15.1.0",
"lodash.template": "^4.5.0",
"lru-cache": "^10.0.1",
"lru-cache": "^10.0.2",
"markdown-it": "^13.0.2",
"markdown-it-anchor": "^8.6.7",
"markdown-it-attrs": "^4.1.6",
@ -169,20 +170,20 @@
"markdown-it-mathjax3": "^4.3.2",
"micromatch": "^4.0.5",
"minimist": "^1.2.8",
"nanoid": "^5.0.2",
"nanoid": "^5.0.3",
"npm-run-all": "^4.1.5",
"ora": "^7.0.1",
"path-to-regexp": "^6.2.1",
"picocolors": "^1.0.0",
"pkg-dir": "^7.0.0",
"playwright-chromium": "^1.39.0",
"polka": "1.0.0-next.22",
"pkg-dir": "^8.0.0",
"playwright-chromium": "^1.40.0",
"polka": "1.0.0-next.23",
"postcss-prefix-selector": "^1.16.0",
"prettier": "^3.0.3",
"prettier": "^3.1.0",
"prompts": "^2.4.2",
"punycode": "^2.3.0",
"punycode": "^2.3.1",
"rimraf": "^5.0.5",
"rollup": "^4.1.4",
"rollup": "^4.5.0",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-esbuild": "^6.1.0",
"semver": "^7.5.4",
@ -192,9 +193,9 @@
"sitemap": "^7.1.1",
"supports-color": "^9.4.0",
"typescript": "^5.2.2",
"vitest": "^0.34.6",
"vue-tsc": "^1.8.19",
"wait-on": "^7.0.1"
"vitest": "^1.0.0-beta.4",
"vue-tsc": "^1.8.22",
"wait-on": "^7.2.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
@ -207,6 +208,13 @@
"pnpm": {
"overrides": {
"ora>string-width": "^5"
},
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights",
"postcss"
]
}
}
}

File diff suppressed because it is too large Load Diff

@ -74,13 +74,13 @@ export function initData(route: Route): VitePressData {
appearance === 'force-dark'
? ref(true)
: appearance
? useDark({
storageKey: APPEARANCE_KEY,
initialValue: () =>
typeof appearance === 'string' ? appearance : 'auto',
...(typeof appearance === 'object' ? appearance : {})
})
: ref(false)
? useDark({
storageKey: APPEARANCE_KEY,
initialValue: () =>
typeof appearance === 'string' ? appearance : 'auto',
...(typeof appearance === 'object' ? appearance : {})
})
: ref(false)
return {
site,

@ -48,7 +48,7 @@ const VitePressApp = defineComponent({
})
})
if (import.meta.env.PROD) {
if (import.meta.env.PROD && site.value.router.prefetchLinks) {
// in prod mode, enable intersectionObserver based pre-fetch
usePrefetch()
}

@ -1,5 +1,6 @@
import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue'
import { lookup } from 'mrmime'
import { notFoundPageData } from '../shared'
import type { PageData, PageDataPayload, Awaitable } from '../shared'
import { inBrowser, withBase } from './utils'
@ -181,7 +182,7 @@ export function createRouter(
link.baseURI
)
const currentUrl = window.location
const extMatch = pathname.match(/\.\w+$/)
const mimeType = lookup(pathname)
// only intercept inbound links
if (
!e.ctrlKey &&
@ -190,8 +191,8 @@ export function createRouter(
!e.metaKey &&
!target &&
origin === currentUrl.origin &&
// don't intercept if non-html extension is present
!(extMatch && extMatch[0] !== '.html')
// intercept only html and unknown types (assume html)
(!mimeType || mimeType === 'text/html')
) {
e.preventDefault()
if (

@ -18,7 +18,6 @@ defineEmits<{
const { theme, frontmatter } = useData()
const { hasSidebar } = useSidebar()
// @ts-ignore
const { y } = useWindowScroll()
const headers = shallowRef<MenuItem[]>([])

@ -20,7 +20,6 @@ defineEmits<{
(e: 'toggle-screen'): void
}>()
// @ts-ignore
const { y } = useWindowScroll()
const { hasSidebar } = useSidebar()
const { frontmatter } = useData()

@ -1,5 +1,5 @@
<script lang="ts" setup>
import { inject } from 'vue'
import { inject, computed } from 'vue'
import { useData } from '../composables/data'
import VPSwitch from './VPSwitch.vue'
import VPIconMoon from './icons/VPIconMoon.vue'
@ -10,11 +10,15 @@ const { isDark } = useData()
const toggleAppearance = inject('toggle-appearance', () => {
isDark.value = !isDark.value
})
const switchTitle = computed(() => {
return isDark.value ? 'Switch to light theme' : 'Switch to dark theme'
})
</script>
<template>
<VPSwitch
title="toggle dark mode"
:title="switchTitle"
class="VPSwitchAppearance"
:aria-checked="isDark"
@click="toggleAppearance"

@ -73,8 +73,8 @@ export function resolveHeaders(
typeof levelsRange === 'number'
? [levelsRange, levelsRange]
: levelsRange === 'deep'
? [2, 6]
: levelsRange
? [2, 6]
: levelsRange
headers = headers.filter((h) => h.level >= high && h.level <= low)

@ -30,8 +30,8 @@ export function usePrevNext() {
(typeof frontmatter.value.prev === 'string'
? frontmatter.value.prev
: typeof frontmatter.value.prev === 'object'
? frontmatter.value.prev.text
: undefined) ??
? frontmatter.value.prev.text
: undefined) ??
candidates[index - 1]?.docFooterText ??
candidates[index - 1]?.text,
link:
@ -46,8 +46,8 @@ export function usePrevNext() {
(typeof frontmatter.value.next === 'string'
? frontmatter.value.next
: typeof frontmatter.value.next === 'object'
? frontmatter.value.next.text
: undefined) ??
? frontmatter.value.next.text
: undefined) ??
candidates[index + 1]?.docFooterText ??
candidates[index + 1]?.text,
link:

@ -104,8 +104,8 @@ export function hasActiveLink(
return isActive(path, items.link)
? true
: items.items
? hasActiveLink(path, items.items)
: false
? hasActiveLink(path, items.items)
: false
}
function addBase(items: SidebarItem[], _base?: string): SidebarItem[] {

@ -1,4 +1,5 @@
import { withBase } from 'vitepress'
import { lookup } from 'mrmime'
import { useData } from '../composables/data'
import { isExternal } from '../../shared'
@ -27,7 +28,7 @@ export function normalizeLink(url: string): string {
isExternal(url) ||
url.startsWith('#') ||
!protocol.startsWith('http') ||
/\.(?!html|md)\w+($|\?)/i.test(url)
(/\.(?!html|md)\w+($|\?)/i.test(url) && lookup(url))
)
return url

@ -77,8 +77,8 @@ export async function bundle(
? 'esbuild'
: false
: typeof options.minify === 'boolean'
? options.minify
: !process.env.DEBUG,
? options.minify
: !process.env.DEBUG,
outDir: ssr ? config.tempDir : config.outDir,
cssCodeSplit: false,
rollupOptions: {

@ -17,6 +17,7 @@ import {
type PageData,
type SSGContext
} from '../shared'
import { version } from '../../../package.json'
export async function renderPage(
render: (path: string) => Promise<SSGContext>,
@ -73,16 +74,16 @@ export async function renderPage(
config.mpa || (!hasCustom404 && page === '404.md')
? []
: result && appChunk
? [
...new Set([
// resolve imports for index.js + page.md.js and inject script tags
// for them as well so we fetch everything as early as possible
// without having to wait for entry chunks to parse
...resolvePageImports(config, page, result, appChunk),
pageClientJsFileName
])
]
: []
? [
...new Set([
// resolve imports for index.js + page.md.js and inject script tags
// for them as well so we fetch everything as early as possible
// without having to wait for entry chunks to parse
...resolvePageImports(config, page, result, appChunk),
pageClientJsFileName
])
]
: []
let prefetchLinks: string[] = []
@ -162,6 +163,7 @@ export async function renderPage(
? ''
: `<meta name="description" content="${description}">`
}
<meta name="generator" content="VitePress v${version}">
${stylesheetLink}
${metadataScript.inHead ? metadataScript.html : ''}
${

@ -13,6 +13,7 @@ import { DEFAULT_THEME_PATH } from './alias'
import { resolvePages } from './plugins/dynamicRoutesPlugin'
import {
APPEARANCE_KEY,
slash,
type DefaultTheme,
type HeadConfig,
type SiteData
@ -74,7 +75,7 @@ export async function resolveConfig(
const site = await resolveSiteData(root, userConfig)
const srcDir = normalizePath(path.resolve(root, userConfig.srcDir || '.'))
const assetsDir = userConfig.assetsDir
? userConfig.assetsDir.replace(/\//g, '')
? slash(userConfig.assetsDir).replace(/^\.?\/|\/$/g, '')
: 'assets'
const outDir = userConfig.outDir
? normalizePath(path.resolve(root, userConfig.outDir))
@ -83,6 +84,18 @@ export async function resolveConfig(
? normalizePath(path.resolve(root, userConfig.cacheDir))
: resolve(root, 'cache')
const resolvedAssetsDir = normalizePath(path.resolve(outDir, assetsDir))
if (!resolvedAssetsDir.startsWith(outDir)) {
throw new Error(
[
`assetsDir cannot be set to a location outside of the outDir.`,
`outDir: ${outDir}`,
`assetsDir: ${assetsDir}`,
`resolved: ${resolvedAssetsDir}`
].join('\n ')
)
}
// resolve theme path
const userThemeDir = resolve(root, 'theme')
const themeDir = (await fs.pathExists(userThemeDir))
@ -231,6 +244,9 @@ export async function resolveSiteData(
description: userConfig.description || 'A VitePress site',
base: userConfig.base ? userConfig.base.replace(/([^/])$/, '$1/') : '/',
head: resolveSiteDataHead(userConfig),
router: {
prefetchLinks: userConfig.router?.prefetchLinks ?? true
},
appearance: userConfig.appearance ?? true,
themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {},
@ -252,8 +268,8 @@ function resolveSiteDataHead(userConfig?: UserConfig): HeadConfig[] {
typeof userConfig?.appearance === 'string'
? userConfig?.appearance
: typeof userConfig?.appearance === 'object'
? userConfig.appearance.initialValue ?? 'auto'
: 'auto'
? userConfig.appearance.initialValue ?? 'auto'
: 'auto'
head.push([
'script',

@ -43,7 +43,6 @@ export async function createMarkdownToVueRenderFn(
srcDir: string,
options: MarkdownOptions = {},
pages: string[],
userDefines: Record<string, any> | undefined,
isBuild = false,
base = '/',
includeLastUpdatedData = false,
@ -57,7 +56,6 @@ export async function createMarkdownToVueRenderFn(
siteConfig?.logger
)
pages = pages.map((p) => slash(p.replace(/\.md$/, '')))
const replaceRegex = genReplaceRegexp(userDefines, isBuild)
return async (
src: string,
@ -200,14 +198,9 @@ export async function createMarkdownToVueRenderFn(
const vueSrc = [
...injectPageDataCode(
sfcBlocks?.scripts.map((item) => item.content) ?? [],
pageData,
replaceRegex
pageData
),
`<template><div>${replaceConstants(
html,
replaceRegex,
vueTemplateBreaker
)}</div></template>`,
`<template><div>${html}</div></template>`,
...(sfcBlocks?.styles.map((item) => item.content) ?? []),
...(sfcBlocks?.customBlocks.map((item) => item.content) ?? [])
].join('\n')
@ -233,46 +226,10 @@ const scriptSetupRE = /<\s*script[^>]*\bsetup\b[^>]*/
const scriptClientRE = /<\s*script[^>]*\bclient\b[^>]*/
const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/
const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/
const jsStringBreaker = '\u200b'
const vueTemplateBreaker = '<wbr>'
function genReplaceRegexp(
userDefines: Record<string, any> = {},
isBuild: boolean
): RegExp {
// `process.env` need to be handled in both dev and build
// @see https://github.com/vitejs/vite/blob/cad27ee8c00bbd5aeeb2be9bfb3eb164c1b77885/packages/vite/src/node/plugins/clientInjections.ts#L57-L64
const replacements = ['process.env']
if (isBuild) {
replacements.push('import.meta', ...Object.keys(userDefines))
}
return new RegExp(
`\\b(${replacements
.map((key) => key.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'))
.join('|')})`,
'g'
)
}
/**
* To avoid env variables being replaced by vite:
* - insert `'\u200b'` char into those strings inside js string (page data)
* - insert `<wbr>` tag into those strings inside html string (vue template)
*
* @see https://vitejs.dev/guide/env-and-mode.html#production-replacement
*/
function replaceConstants(str: string, replaceRegex: RegExp, breaker: string) {
return str.replace(replaceRegex, (_) => `${_[0]}${breaker}${_.slice(1)}`)
}
function injectPageDataCode(
tags: string[],
data: PageData,
replaceRegex: RegExp
) {
const dataJson = JSON.stringify(data)
function injectPageDataCode(tags: string[], data: PageData) {
const code = `\nexport const __pageData = JSON.parse(${JSON.stringify(
replaceConstants(dataJson, replaceRegex, jsStringBreaker)
JSON.stringify(data)
)})`
const existingScriptIndex = tags.findIndex((tag) => {

@ -133,7 +133,6 @@ export async function createVitePressPlugin(
srcDir,
markdown,
pages,
config.define,
config.command === 'build',
config.base,
lastUpdated,
@ -328,14 +327,11 @@ export async function createVitePressPlugin(
generateBundle(_options, bundle) {
if (ssr) {
// @ts-ignore will be removed in vite 5
if (config.ssr?.format !== 'cjs') {
this.emitFile({
type: 'asset',
fileName: 'package.json',
source: '{ "private": true, "type": "module" }'
})
}
this.emitFile({
type: 'asset',
fileName: 'package.json',
source: '{ "private": true, "type": "module" }'
})
} else {
// client build:
// for each .md entry chunk, adjust its name to its correct path.
@ -350,6 +346,10 @@ export async function createVitePressPlugin(
bundle[name + '-lean'] = {
...chunk,
fileName: chunk.fileName.replace(/\.js$/, '.lean.js'),
preliminaryFileName: chunk.preliminaryFileName.replace(
/\.js$/,
'.lean.js'
),
code: chunk.code.replace(staticStripRE, `""`)
}

@ -69,6 +69,10 @@ export interface UserConfig<ThemeConfig = any>
locales?: LocaleConfig<ThemeConfig>
router?: {
prefetchLinks?: boolean
}
appearance?:
| boolean
| 'dark'
@ -201,6 +205,7 @@ export interface SiteConfig<ThemeConfig = any>
| 'vue'
| 'vite'
| 'shouldPreload'
| 'router'
| 'mpa'
| 'metaChunk'
| 'lastUpdated'

3
types/shared.d.ts vendored

@ -126,6 +126,9 @@ export interface SiteData<ThemeConfig = any> {
locales: LocaleConfig<ThemeConfig>
localeIndex?: string
contentProps?: Record<string, any>
router: {
prefetchLinks: boolean
}
}
export type HeadConfig =

Loading…
Cancel
Save