Merge branch 'main' into feat/load-page-outline-link-scroll-to-center

pull/4634/head
btea 1 month ago committed by GitHub
commit 013160ee67
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -23,7 +23,7 @@ Hi! We're really excited that you are interested in contributing to VitePress. B
## Development Setup ## Development Setup
You will need [pnpm](https://pnpm.io) You will need [Node.js](https://nodejs.org) v20 or higher and [pnpm](https://pnpm.io).
After cloning the repo, run: After cloning the repo, run:

@ -9,6 +9,7 @@ on:
types: [opened, synchronize, labeled, ready_for_review] types: [opened, synchronize, labeled, ready_for_review]
paths-ignore: paths-ignore:
- '.github/**' - '.github/**'
- '!.github/workflows/cr.yml'
- '__tests__/**' - '__tests__/**'
- 'art/**' - 'art/**'
- 'docs/**' - 'docs/**'
@ -17,6 +18,7 @@ on:
branches: [main] branches: [main]
paths-ignore: paths-ignore:
- '.github/**' - '.github/**'
- '!.github/workflows/cr.yml'
- '__tests__/**' - '__tests__/**'
- 'art/**' - 'art/**'
- 'docs/**' - 'docs/**'

@ -18,7 +18,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest]
node_version: [18, 20, 22] node_version: [20, 22, latest]
include: include:
- os: windows-latest - os: windows-latest
node_version: 22 node_version: 22

@ -1,3 +1,99 @@
## [2.0.0-alpha.9](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.8...v2.0.0-alpha.9) (2025-07-26)
### Bug Fixes
- **md:** pass container option to gitHubAlertsPlugin ([#4848](https://github.com/vuejs/vitepress/issues/4848)) ([52f0eaa](https://github.com/vuejs/vitepress/commit/52f0eaa0849344aa45efbf7258a6287597e55a9a))
- **theme:** remove duplicate text in sponsors grid ([3c51b22](https://github.com/vuejs/vitepress/commit/3c51b22ac98a12f193081d23799cb9f3f2ecf682)), closes [#4854](https://github.com/vuejs/vitepress/issues/4854)
### Features
- **search:** upgrade search to DocSearch v4-beta ([#4843](https://github.com/vuejs/vitepress/issues/4843)) ([ac61abe](https://github.com/vuejs/vitepress/commit/ac61abe7d7be5ef8b6939f18192896538eba1b8c))
### BREAKING CHANGES
- **search:** Uses DocSearch v4 beta. No change is required if you're not customizing the styles of navbar search button or modal. DocSearch AI features are in private beta, you can apply for them at https://forms.gle/iyfb5pC2CiiwszUKA
## [2.0.0-alpha.8](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.7...v2.0.0-alpha.8) (2025-07-08)
### Bug Fixes
- adjust glob logic to always resolve glob relative to base ([5d41785](https://github.com/vuejs/vitepress/commit/5d41785ff7b016b08f587f1ef3318fc18d58f6ab)), closes [#4822](https://github.com/vuejs/vitepress/issues/4822)
- **build:** ignore escaped `:` when splitting selector in `postcssIsolateStyles` ([#4830](https://github.com/vuejs/vitepress/issues/4830)) ([a629b03](https://github.com/vuejs/vitepress/commit/a629b03f0ee8a29d73a18481399d7de1c992faf2))
- font preload not being generated in rolldown-vite ([ed387e8](https://github.com/vuejs/vitepress/commit/ed387e89d42a08c15a9f45c9c5e11c6750245490))
- **theme:** remove extra slash when concatenating base with sidebar links ([c8fc80e](https://github.com/vuejs/vitepress/commit/c8fc80e438fffd98feaf7c72263bc3077792c4a2))
## [2.0.0-alpha.7](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.6...v2.0.0-alpha.7) (2025-06-24)
### Bug Fixes
- **local-search:** parse headings with non-anchor `a` tags as titles properly ([#4809](https://github.com/vuejs/vitepress/issues/4809)) ([5359903](https://github.com/vuejs/vitepress/commit/53599039a01af6d8e17a6a6e9cea5c222cc5948c))
- resolve pages after setting global vitepress config ([56ba65e](https://github.com/vuejs/vitepress/commit/56ba65e1301454df88f9a3856fa1a70dc052d314)), closes [#4803](https://github.com/vuejs/vitepress/issues/4803)
### Features
- **router:** add `replace` option to `useRouter` for history management ([#4788](https://github.com/vuejs/vitepress/issues/4788)) ([23541b4](https://github.com/vuejs/vitepress/commit/23541b4f83726cdac09ffcaf9141bba871cda690)), closes [#4787](https://github.com/vuejs/vitepress/issues/4787)
- consistent glob options across content, data, and path loaders ([#4808](https://github.com/vuejs/vitepress/issues/4808)) ([7619521](https://github.com/vuejs/vitepress/commit/76195212596cd54095240246b7e78075ac3cbc27)), closes [#4807](https://github.com/vuejs/vitepress/issues/4807)
- bump to vite 7 ([2ecd607](https://github.com/vuejs/vitepress/commit/2ecd607af15222eeddf0b888a72d0f913f5a3cd2))
### Performance Improvements
- render pages in contentLoader asynchronously ([36148a0](https://github.com/vuejs/vitepress/commit/36148a0bcf3a73d1fe3f0c5f33337b679f700053))
### BREAKING CHANGES
- Only `cwd`, `ignore`, `dot` and `debug` are supported in `globOptions` of `createContentLoader`. If you want to pass other options, you still can but you might need to suppress type errors.
- Uses vite 7. See [vite migration guide](https://vite.dev/guide/migration.html) for more info. For most of the users no change is required. VitePress should work same as earlier, except for maybe some type mismatches if you're using third-party plugins. You can suppress them using `@ts-expect-error` or `as any` and report the issues at respective repositories.
## [2.0.0-alpha.6](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.5...v2.0.0-alpha.6) (2025-06-12)
### Bug Fixes
- allow AdditionalConfigLoader to return void ([906a44a](https://github.com/vuejs/vitepress/commit/906a44a3ad488a46804757326af95cfb8cac6b75))
- **build:** avoiding creating separate chunks for vite public assets ([21f24b9](https://github.com/vuejs/vitepress/commit/21f24b9994ea4807ac7e0be38408e9aaa3abe8a9))
- **build:** emit lean chunks after vite has done processing ([26cb685](https://github.com/vuejs/vitepress/commit/26cb685adf54f07fe3e9fd7bfd49a0ff79956923)), closes [#4737](https://github.com/vuejs/vitepress/issues/4737)
- **client:** properly skip removed lines when copying code blocks ([c128baf](https://github.com/vuejs/vitepress/commit/c128baf0c41d5113c1b876f691e0185201b1f500))
- disable appearance scripts in zero-js mode ([e7f9d05](https://github.com/vuejs/vitepress/commit/e7f9d05c3e2ef4f4c1db3b2c17e586f0fc26a6f6)), closes [#4766](https://github.com/vuejs/vitepress/issues/4766)
- don't preload dynamic imports ([801648a](https://github.com/vuejs/vitepress/commit/801648a4c9d91e7f96302932ac9247d5bdd64ef7)), closes [#4770](https://github.com/vuejs/vitepress/issues/4770)
- gather additional config files even if root .vitepress/config is not present ([26f178c](https://github.com/vuejs/vitepress/commit/26f178cfaa330a017bb69b1ec6bd482d63a100a9))
- set `preserveEntrySignatures` for rolldown-vite ([#4784](https://github.com/vuejs/vitepress/issues/4784)) ([4351bc0](https://github.com/vuejs/vitepress/commit/4351bc0b831277401e08b350d7d7c0ab9ea0c9ed))
- skip fields not supported by rolldown for rolldown-vite ([#4747](https://github.com/vuejs/vitepress/issues/4747)) ([4e3fce4](https://github.com/vuejs/vitepress/commit/4e3fce40c9bab261f3c5e31833475c3e2c6ba0cf))
- **theme/regression:** code blocks not aligned properly in rtl layouts ([a643347](https://github.com/vuejs/vitepress/commit/a64334753079a5b874a482508d9ee255d2a0ea38))
- **theme:** hide native search input cancel button ([#4723](https://github.com/vuejs/vitepress/issues/4723)) ([2c4944f](https://github.com/vuejs/vitepress/commit/2c4944f06ccf46fcf58fb18a1819fd167c9533cc))
- **theme:** prevent error in handleSearchHotKey method ([#4782](https://github.com/vuejs/vitepress/issues/4782)) ([21fcecc](https://github.com/vuejs/vitepress/commit/21fcecce0581d0c461bc15e03429f61ff444a655))
- use v-pre for mathjax instead of isCustomElement ([c9b8928](https://github.com/vuejs/vitepress/commit/c9b89282f3573998cfc4103bbddbd73d2529cb66))
### Features
- use `oxc-minify` instead of `transformWithEsbuild` when rolldown-vite is used ([#4748](https://github.com/vuejs/vitepress/issues/4748)) ([7c1dc48](https://github.com/vuejs/vitepress/commit/7c1dc48b2fd08e128f7bbe26690fb6534dfb4b95))
## [2.0.0-alpha.5](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.4...v2.0.0-alpha.5) (2025-04-21)
### Bug Fixes
- don't remove shiki styles from `pre` and remove unnecessary transformers (#4652) ([db58af5](https://github.com/vuejs/vitepress/commit/db58af5c66e563e7663084057a9853d8f2da984c)), closes [#4652](https://github.com/vuejs/vitepress/issues/4652)
- normalize url fragments in internal links to correctly resolve to anchors ([#4628](https://github.com/vuejs/vitepress/issues/4628)) ([e25d080](https://github.com/vuejs/vitepress/commit/e25d0805505db2f1116e99d38a488d5cb39ed426)), closes [#4605](https://github.com/vuejs/vitepress/issues/4605)
- **theme-default:** ensure proper sizing of SVG hero images ([#4639](https://github.com/vuejs/vitepress/issues/4639)) ([7d94481](https://github.com/vuejs/vitepress/commit/7d9448192079e59493aa5c1e86cdf6d6deae8e36))
### Features
- add `isHome` frontmatter option (#4673) ([544cd81](https://github.com/vuejs/vitepress/commit/544cd8125985b9e3af7fee68ea9592d159799e01)), closes [#4673](https://github.com/vuejs/vitepress/issues/4673)
- add `custom-block-title-default` class when default title is used for containers ([#4643](https://github.com/vuejs/vitepress/issues/4643)) ([63079bf](https://github.com/vuejs/vitepress/commit/63079bff03b15861d174199f7361a2aff84380e0))
- add `dir=ltr` by default on code block pre elements instead of relying on css ([19faa16](https://github.com/vuejs/vitepress/commit/19faa16169b44f52bedf1401b4a97b2a8ffdeacb))
- **default-theme:** make VPButton slottable ([#4689](https://github.com/vuejs/vitepress/issues/4689)) ([0b70397](https://github.com/vuejs/vitepress/commit/0b7039719782e85119ad22be5c89ef3d233ffaae))
- support distributed config files ([#4660](https://github.com/vuejs/vitepress/issues/4660)) ([c5e2e4d](https://github.com/vuejs/vitepress/commit/c5e2e4db818c06f3c1b458753f22fb6ec1609628))
- **theme:** make "Take me home" button's link customizable ([#4658](https://github.com/vuejs/vitepress/issues/4658)) ([0267dca](https://github.com/vuejs/vitepress/commit/0267dcafa20beea24ef359d24bb1fa99e1ffda49))
### Performance Improvements
- call `module.enableCompileCache()` ([70de34c](https://github.com/vuejs/vitepress/commit/70de34c0387d9668ada3ea9a795f9ebee3535f5b))
- hoist expensive operations in useLayout ([e5ab067](https://github.com/vuejs/vitepress/commit/e5ab0676a9a8dc607e213eb691439b2e4ee472b7))
### BREAKING CHANGES
- `useLocalNav` and `useSidebar` are removed in favor of `useLayout`. To migrate, just do find and replace. Sidebar controls are no longer exported, but we didn't find any usage on GitHub. If there is demand, we can export respective composables later. `DefaultTheme.DocSidebar` and `DefaultTheme.DocLocalNav` types are also removed.
- `vp-adaptive-theme` class is no longer added to code blocks when there is single theme. Theme authors supporting single code theme can use `.shiki:not(.shiki-themes)` as selector. Alternatively, it might be better to use the bg/fg variables set on the `.shiki` block to keep things generic.
- `vp-code` class is no longer added to code blocks. Use `.shiki` or `pre.shiki` or `[class*='language-'] pre` instead. People not customizing their themes are not affected.
## [2.0.0-alpha.4](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.3...v2.0.0-alpha.4) (2025-03-09) ## [2.0.0-alpha.4](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.3...v2.0.0-alpha.4) (2025-03-09)
### Bug Fixes ### Bug Fixes
@ -2198,7 +2294,6 @@ This version uses Vue 3.2.0.
### BREAKING CHANGES ### BREAKING CHANGES
- Some config options have changed. - Some config options have changed.
- `vueOptions` renamed to `vue` - `vueOptions` renamed to `vue`
- `alias` option has been removed. Use `vite.resovle.alias` instead. - `alias` option has been removed. Use `vite.resovle.alias` instead.
@ -2216,7 +2311,6 @@ This version uses Vue 3.2.0.
### BREAKING CHANGES ### BREAKING CHANGES
- The following methods are removed. - The following methods are removed.
- `useSiteData` - `useSiteData`
- `useSiteDataByRoute` - `useSiteDataByRoute`
- `usePageData` - `usePageData`

@ -1,6 +1,6 @@
# VitePress 📝💨 # VitePress 📝💨
[![test](https://github.com/vuejs/vitepress/workflows/Test/badge.svg)](https://github.com/vuejs/vitepress/actions) [![test](https://github.com/vuejs/vitepress/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/vuejs/vitepress/actions/workflows/test.yml)
[![npm](https://img.shields.io/npm/v/vitepress)](https://www.npmjs.com/package/vitepress) [![npm](https://img.shields.io/npm/v/vitepress)](https://www.npmjs.com/package/vitepress)
[![nightly releases](https://img.shields.io/badge/nightly-releases-orange)](https://nightly.akryum.dev/vuejs/vitepress) [![nightly releases](https://img.shields.io/badge/nightly-releases-orange)](https://nightly.akryum.dev/vuejs/vitepress)
[![chat](https://img.shields.io/badge/chat-discord-blue?logo=discord)](https://chat.vuejs.org) [![chat](https://img.shields.io/badge/chat-discord-blue?logo=discord)](https://chat.vuejs.org)

@ -30,7 +30,7 @@ function removeSpaces(str: string) {
<input <input
type="radio" type="radio"
:id="option.key" :id="option.key"
:name="name" :name
:value="option.value" :value="option.value"
v-model="selected" v-model="selected"
/> />

@ -0,0 +1,44 @@
import {
postcssIsolateStyles,
splitSelectorPseudo
} from 'node/postcss/isolateStyles'
// helper to run plugin transform on selector
function apply(
prefixPlugin: ReturnType<typeof postcssIsolateStyles>,
selector: string
) {
// `prepare` is available on the runtime plugin but missing from the types, thus cast to `any`
const { Rule } = (prefixPlugin as any).prepare({
root: { source: { input: { file: 'foo/base.css' } } }
})
const rule = { selectors: [selector] }
Rule(rule, { result: {} })
return rule.selectors[0]
}
describe('node/postcss/isolateStyles', () => {
const plugin = postcssIsolateStyles()
test('splitSelectorPseudo skips escaped colon', () => {
const input = '.foo\\:bar'
const [selector, pseudo] = splitSelectorPseudo(input)
expect(selector).toBe(input)
expect(pseudo).toBe('')
})
test('splitSelectorPseudo splits on pseudo selectors', () => {
const input = '.button:hover'
const [selector, pseudo] = splitSelectorPseudo(input)
expect(selector).toBe('.button')
expect(pseudo).toBe(':hover')
})
it('postcssIsolateStyles inserts :not(...) in the right place', () => {
const input = '.disabled\\:opacity-50:disabled'
const result = apply(plugin, input)
expect(result).toBe(
'.disabled\\:opacity-50:not(:where(.vp-raw, .vp-raw *)):disabled'
)
})
})

@ -1,2 +1,16 @@
#!/usr/bin/env node #!/usr/bin/env node
// @ts-check
import module from 'node:module'
// https://github.com/vitejs/vite/blob/6c8a5a27e645a182f5b03a4ed6aa726eab85993f/packages/vite/bin/vite.js#L48-L63
try {
module.enableCompileCache?.()
setTimeout(() => {
try {
module.flushCompileCache?.()
} catch {}
}, 10 * 1000).unref()
} catch {}
import('../dist/node/cli.js') import('../dist/node/cli.js')

@ -1,17 +1,18 @@
import { defineConfig } from 'vitepress' import {
defineConfig,
resolveSiteDataByRoute,
type HeadConfig
} from 'vitepress'
import { import {
groupIconMdPlugin, groupIconMdPlugin,
groupIconVitePlugin, groupIconVitePlugin,
localIconLoader localIconLoader
} from 'vitepress-plugin-group-icons' } from 'vitepress-plugin-group-icons'
import { search as esSearch } from './es' import llmstxt from 'vitepress-plugin-llms'
import { search as faSearch } from './fa'
import { search as koSearch } from './ko' const prod = !!process.env.NETLIFY
import { search as ptSearch } from './pt'
import { search as ruSearch } from './ru'
import { search as zhSearch } from './zh'
export const shared = defineConfig({ export default defineConfig({
title: 'VitePress', title: 'VitePress',
rewrites: { rewrites: {
@ -71,18 +72,35 @@ export const shared = defineConfig({
} }
}, },
/* prettier-ignore */
head: [ head: [
['link', { rel: 'icon', type: 'image/svg+xml', href: '/vitepress-logo-mini.svg' }], [
['link', { rel: 'icon', type: 'image/png', href: '/vitepress-logo-mini.png' }], 'link',
{ rel: 'icon', type: 'image/svg+xml', href: '/vitepress-logo-mini.svg' }
],
[
'link',
{ rel: 'icon', type: 'image/png', href: '/vitepress-logo-mini.png' }
],
['meta', { name: 'theme-color', content: '#5f67ee' }], ['meta', { name: 'theme-color', content: '#5f67ee' }],
['meta', { property: 'og:type', content: 'website' }], ['meta', { property: 'og:type', content: 'website' }],
['meta', { property: 'og:locale', content: 'en' }],
['meta', { property: 'og:title', content: 'VitePress | Vite & Vue Powered Static Site Generator' }],
['meta', { property: 'og:site_name', content: 'VitePress' }], ['meta', { property: 'og:site_name', content: 'VitePress' }],
['meta', { property: 'og:image', content: 'https://vitepress.dev/vitepress-og.jpg' }], [
'meta',
{
property: 'og:image',
content: 'https://vitepress.dev/vitepress-og.jpg'
}
],
['meta', { property: 'og:url', content: 'https://vitepress.dev/' }], ['meta', { property: 'og:url', content: 'https://vitepress.dev/' }],
['script', { src: 'https://cdn.usefathom.com/script.js', 'data-site': 'AZBRSFGG', 'data-spa': 'auto', defer: '' }] [
'script',
{
src: 'https://cdn.usefathom.com/script.js',
'data-site': 'AZBRSFGG',
'data-spa': 'auto',
defer: ''
}
]
], ],
themeConfig: { themeConfig: {
@ -98,30 +116,56 @@ export const shared = defineConfig({
appId: '8J64VVRP8K', appId: '8J64VVRP8K',
apiKey: '52f578a92b88ad6abde815aae2b0ad7c', apiKey: '52f578a92b88ad6abde815aae2b0ad7c',
indexName: 'vitepress', indexName: 'vitepress',
locales: { askAi: 'YaVSonfX5bS8'
...zhSearch,
...ptSearch,
...ruSearch,
...esSearch,
...koSearch,
...faSearch
}
} }
}, },
carbonAds: { code: 'CEBDT27Y', placement: 'vuejsorg' } carbonAds: { code: 'CEBDT27Y', placement: 'vuejsorg' }
}, },
locales: {
root: { label: 'English' },
zh: { label: '简体中文' },
pt: { label: 'Português' },
ru: { label: 'Русский' },
es: { label: 'Español' },
ko: { label: '한국어' },
fa: { label: 'فارسی' }
},
vite: { vite: {
plugins: [ plugins: [
groupIconVitePlugin({ groupIconVitePlugin({
customIcon: { customIcon: {
vitepress: localIconLoader( vitepress: localIconLoader(
import.meta.url, import.meta.url,
'../../public/vitepress-logo-mini.svg' '../public/vitepress-logo-mini.svg'
), ),
firebase: 'logos:firebase' firebase: 'logos:firebase'
} }
}),
prod &&
llmstxt({
workDir: 'en',
ignoreFiles: ['index.md']
}) })
] ],
experimental: {
enableNativePlugin: true
}
},
transformPageData: prod
? (pageData, ctx) => {
const site = resolveSiteDataByRoute(
ctx.siteConfig.site,
pageData.relativePath
)
const title = `${pageData.title || site.title} | ${pageData.description || site.description}`
;((pageData.frontmatter.head ??= []) as HeadConfig[]).push(
['meta', { property: 'og:locale', content: site.lang }],
['meta', { property: 'og:title', content: title }]
)
} }
: undefined
}) })

@ -1,22 +0,0 @@
import { defineConfig } from 'vitepress'
import { shared } from './shared'
import { en } from './en'
import { zh } from './zh'
import { pt } from './pt'
import { ru } from './ru'
import { es } from './es'
import { ko } from './ko'
import { fa } from './fa'
export default defineConfig({
...shared,
locales: {
root: { label: 'English', ...en },
zh: { label: '简体中文', ...zh },
pt: { label: 'Português', ...pt },
ru: { label: 'Русский', ...ru },
es: { label: 'Español', ...es },
ko: { label: '한국어', ...ko },
fa: { label: 'فارسی', ...fa }
}
})

@ -1,5 +1,3 @@
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100..900&display=swap');
:root:where(:lang(fa)) { :root:where(:lang(fa)) {
--vp-font-family-base: --vp-font-family-base:
'Vazirmatn', 'Inter', ui-sans-serif, system-ui, sans-serif, 'Vazirmatn', 'Inter', ui-sans-serif, system-ui, sans-serif,

@ -1,10 +1,10 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const en = defineConfig({ export default defineAdditionalConfig({
lang: 'en-US', lang: 'en-US',
description: 'Vite & Vue powered static site generator.', description: 'Vite & Vue powered static site generator.',

@ -111,7 +111,7 @@ Set up a new project and change these settings using your dashboard:
- **Build Command:** `npm run docs:build` - **Build Command:** `npm run docs:build`
- **Output Directory:** `docs/.vitepress/dist` - **Output Directory:** `docs/.vitepress/dist`
- **Node Version:** `18` (or above) - **Node Version:** `20` (or above)
::: warning ::: warning
Don't enable options like _Auto Minify_ for HTML code. It will remove comments from output which have meaning to Vue. You may see hydration mismatch errors if they get removed. Don't enable options like _Auto Minify_ for HTML code. It will remove comments from output which have meaning to Vue. You may see hydration mismatch errors if they get removed.
@ -163,7 +163,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # or pnpm / yarn cache: npm # or pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ If your font is a local file referenced via `@font-face`, it will be processed a
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// adjust the regex accordingly to match your font // adjust the regex accordingly to match your font
const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -252,6 +252,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )
@ -319,7 +320,7 @@ export default defineConfig({
{ {
find: /^.*\/VPNavBar\.vue$/, find: /^.*\/VPNavBar\.vue$/,
replacement: fileURLToPath( replacement: fileURLToPath(
new URL('./components/CustomNavBar.vue', import.meta.url) new URL('./theme/components/CustomNavBar.vue', import.meta.url)
) )
} }
] ]

@ -39,22 +39,6 @@ $ bun add -D vitepress
::: :::
::: details Getting missing peer deps warnings?
If using PNPM, you will notice a missing peer warning for `@docsearch/js`. This does not prevent VitePress from working. If you wish to suppress this warning, add the following to your `package.json`:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip NOTE ::: tip NOTE
VitePress is an ESM-only package. Don't use `require()` to import it, and make sure your nearest `package.json` contains `"type": "module"`, or change the file extension of your relevant files like `.vitepress/config.js` to `.mjs`/`.mts`. Refer to [Vite's troubleshooting guide](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) for more details. Also, inside async CJS contexts, you can use `await import('vitepress')` instead. VitePress is an ESM-only package. Don't use `require()` to import it, and make sure your nearest `package.json` contains `"type": "module"`, or change the file extension of your relevant files like `.vitepress/config.js` to `.mjs`/`.mts`. Refer to [Vite's troubleshooting guide](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) for more details. Also, inside async CJS contexts, you can use `await import('vitepress')` instead.

@ -781,7 +781,7 @@ You can also [import snippets](#import-code-snippets) in code groups:
You can include a markdown file in another markdown file, even nested. You can include a markdown file in another markdown file, even nested.
::: tip ::: tip
You can also prefix the markdown path with `@`, it will act as the source root. By default, it's the VitePress project root, unless `srcDir` is configured. You can also prefix the markdown path with `@`, and it will act as the source root. By default, the source root is the VitePress project root, unless `srcDir` is configured.
::: :::
For example, you can include a relative markdown file using this: For example, you can include a relative markdown file using this:

@ -12,7 +12,7 @@ Just want to try it out? Skip to the [Quickstart](./getting-started).
- **Documentation** - **Documentation**
VitePress ships with a default theme designed for technical documentation. It powers this page you are reading right now, along with the documentation for [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) and [many more](https://www.vuetelescope.com/explore?framework.slug=vitepress). VitePress ships with a default theme designed for technical documentation. It powers this page you are reading right now, along with the documentation for [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) and [many more](https://github.com/search?q=/"vitepress":+/+language:json&type=code).
The [official Vue.js documentation](https://vuejs.org/) is also based on VitePress, but uses a custom theme shared between multiple translations. The [official Vue.js documentation](https://vuejs.org/) is also based on VitePress, but uses a custom theme shared between multiple translations.

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: VitePress
titleTemplate: Vite & Vue Powered Static Site Generator
hero: hero:
name: VitePress name: VitePress
text: Vite & Vue Powered Static Site Generator text: Vite & Vue Powered Static Site Generator

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | Public base path (default: `/`) (`string`) | | `--base <path>` | Public base path (default: `/`) (`string`) |
| `--target <target>` | Transpile target (default: `"modules"`) (`string`) | | `--target <target>` | Transpile target (default: `"modules"`) (`string`) |
| `--outDir <dir>` | Output directory relative to **cwd** (default: `<root>/.vitepress/dist`) (`string`) | | `--outDir <dir>` | Output directory relative to **cwd** (default: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) | | `--assetsInlineLimit <number>` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) |
## `vitepress preview` ## `vitepress preview`

@ -457,3 +457,38 @@ Can be used to customize the label of the skip to content link. This link is sho
- Default: `false` - Default: `false`
Whether to show an external link icon next to external links in markdown. Whether to show an external link icon next to external links in markdown.
## `useLayout` <Badge type="info" text="composable" />
Returns layout-related data. The returned object has the following type:
```ts
interface {
isHome: ComputedRef<boolean>
sidebar: Readonly<ShallowRef<DefaultTheme.SidebarItem[]>>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
headers: Readonly<ShallowRef<DefaultTheme.OutlineItem[]>>
hasLocalNav: ComputedRef<boolean>
}
```
**Example:**
```vue
<script setup>
import { useLayout } from 'vitepress/theme'
const { hasSidebar } = useLayout()
</script>
<template>
<div v-if="hasSidebar">Only show when sidebar exists</div>
</template>
```

@ -2,8 +2,27 @@
The update time of the last content will be displayed in the lower right corner of the page. To enable it, add `lastUpdated` options to your config. The update time of the last content will be displayed in the lower right corner of the page. To enable it, add `lastUpdated` options to your config.
::: tip ::: info
You need to commit the markdown file to see the updated time. VitePress displays the "last updated" time using the timestamp of the most recent Git commit for each file. To enable this, the Markdown file must be committed to Git.
Internally, VitePress runs `git log -1 --pretty="%ai"` on each file to retrieve its timestamp. If all pages show the same update time, it's likely due to shallow cloning (common in CI environments), which limits Git history.
To fix this in **GitHub Actions**, use the following in your workflow:
```yaml{4}
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
```
Other CI/CD platforms have similar settings.
If such options aren't available, you can prepend the `docs:build` command in your `package.json` with a manual fetch:
```json
"docs:build": "git fetch --unshallow && vitepress build docs"
```
::: :::
## Site-Level Config ## Site-Level Config

@ -6,7 +6,7 @@ outline: deep
## Local Search ## Local Search
VitePress supports fuzzy full-text search using a in-browser index thanks to [minisearch](https://github.com/lucaong/minisearch/). To enable this feature, simply set the `themeConfig.search.provider` option to `'local'` in your `.vitepress/config.ts` file: VitePress supports fuzzy full-text search using an in-browser index thanks to [minisearch](https://github.com/lucaong/minisearch/). To enable this feature, simply set the `themeConfig.search.provider` option to `'local'` in your `.vitepress/config.ts` file:
```ts ```ts
import { defineConfig } from 'vitepress' import { defineConfig } from 'vitepress'
@ -233,10 +233,16 @@ export default defineConfig({
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: '清除查询条件', clearButtonTitle: '清除查询条件',
resetButtonAriaLabel: '清除查询条件', clearButtonAriaLabel: '清除查询条件',
cancelButtonText: '取消', closeButtonText: '关闭',
cancelButtonAriaLabel: '取消' closeButtonAriaLabel: '关闭',
placeholderText: '搜索文档',
placeholderTextAskAi: '向 AI 提问:',
placeholderTextAskAiStreaming: '回答中...',
searchInputLabel: '搜索',
backToKeywordSearchButtonText: '返回关键字搜索',
backToKeywordSearchButtonAriaLabel: '返回关键字搜索'
}, },
startScreen: { startScreen: {
recentSearchesTitle: '搜索历史', recentSearchesTitle: '搜索历史',
@ -244,23 +250,48 @@ export default defineConfig({
saveRecentSearchButtonTitle: '保存至搜索历史', saveRecentSearchButtonTitle: '保存至搜索历史',
removeRecentSearchButtonTitle: '从搜索历史中移除', removeRecentSearchButtonTitle: '从搜索历史中移除',
favoriteSearchesTitle: '收藏', favoriteSearchesTitle: '收藏',
removeFavoriteSearchButtonTitle: '从收藏中移除' removeFavoriteSearchButtonTitle: '从收藏中移除',
recentConversationsTitle: '最近的对话',
removeRecentConversationButtonTitle: '从历史记录中删除对话'
}, },
errorScreen: { errorScreen: {
titleText: '无法获取结果', titleText: '无法获取结果',
helpText: '你可能需要检查你的网络连接' helpText: '你可能需要检查你的网络连接'
}, },
footer: {
selectText: '选择',
navigateText: '切换',
closeText: '关闭',
searchByText: '搜索提供者'
},
noResultsScreen: { noResultsScreen: {
noResultsText: '无法找到相关结果', noResultsText: '无法找到相关结果',
suggestedQueryText: '你可以尝试查询', suggestedQueryText: '你可以尝试查询',
reportMissingResultsText: '你认为该查询应该有结果?', reportMissingResultsText: '你认为该查询应该有结果?',
reportMissingResultsLinkText: '点击反馈' reportMissingResultsLinkText: '点击反馈'
},
resultsScreen: {
askAiPlaceholder: '向 AI 提问: '
},
askAiScreen: {
disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。',
relatedSourcesText: '相关来源',
thinkingText: '思考中...',
copyButtonText: '复制',
copyButtonCopiedText: '已复制!',
copyButtonTitle: '复制',
likeButtonTitle: '赞',
dislikeButtonTitle: '踩',
thanksForFeedbackText: '感谢你的反馈!',
preToolCallText: '搜索中...',
duringToolCallText: '搜索 ',
afterToolCallText: '已搜索'
},
footer: {
selectText: '选择',
submitQuestionText: '提交问题',
selectKeyAriaLabel: 'Enter 键',
navigateText: '切换',
navigateUpKeyAriaLabel: '向上箭头',
navigateDownKeyAriaLabel: '向下箭头',
closeText: '关闭',
backToSearchText: '返回搜索',
closeKeyAriaLabel: 'Esc 键',
poweredByText: '搜索提供者'
} }
} }
} }
@ -274,6 +305,43 @@ export default defineConfig({
[These options](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) can be overridden. Refer official Algolia docs to learn more about them. [These options](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) can be overridden. Refer official Algolia docs to learn more about them.
### Algolia Ask AI Support {#ask-ai}
If you would like to include **Ask AI**, pass the `askAi` option (or any of the partial fields) inside `options`:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: '...',
apiKey: '...',
indexName: '...',
// askAi: "YOUR-ASSISTANT-ID"
// OR
askAi: {
// at minimum you must provide the assistantId you received from Algolia
assistantId: 'XXXYYY',
// optional overrides if omitted, the top-level appId/apiKey/indexName values are reused
// apiKey: '...',
// appId: '...',
// indexName: '...'
}
}
}
}
})
```
::: warning Note
If want to default to keyword search and do not want to use Ask AI, just omit the `askAi` property
:::
The translations for the Ask AI UI live under `options.translations.modal.askAiScreen` and `options.translations.resultsScreen` — see the [type definitions](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) for all keys.
### Crawler Config ### Crawler Config
Here is an example config based on what this site uses: Here is an example config based on what this site uses:

@ -180,36 +180,3 @@ export default {
} }
} }
``` ```
## `useSidebar` <Badge type="info" text="composable" />
Returns sidebar-related data. The returned object has the following type:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**Example:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">Only show when sidebar exists</div>
</template>
```

@ -53,12 +53,12 @@ const members = [
Say hello to our awesome team. Say hello to our awesome team.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
``` ```
The above will display a team member in card looking element. It should display something similar to below. The above will display a team member in card looking element. It should display something similar to below.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
`<VPTeamMembers>` component comes in 2 different sizes, `small` and `medium`. While it boils down to your preference, usually `small` size should fit better when used in doc page. Also, you may add more properties to each member such as adding "description" or "sponsor" button. Learn more about it in [`<VPTeamMembers>`](#vpteammembers). `<VPTeamMembers>` component comes in 2 different sizes, `small` and `medium`. While it boils down to your preference, usually `small` size should fit better when used in doc page. Also, you may add more properties to each member such as adding "description" or "sponsor" button. Learn more about it in [`<VPTeamMembers>`](#vpteammembers).
@ -107,9 +107,7 @@ const members = [
team, some of whom have chosen to be featured below. team, some of whom have chosen to be featured below.
</template> </template>
</VPTeamPageTitle> </VPTeamPageTitle>
<VPTeamMembers <VPTeamMembers :members />
:members="members"
/>
</VPTeamPage> </VPTeamPage>
``` ```

@ -225,3 +225,16 @@ Then you can customize styles of this specific page in `.vitepress/theme/custom.
/* page-specific styles */ /* page-specific styles */
} }
``` ```
### isHome
- Type: `boolean`
The default theme relies on checks like `frontmatter.layout === 'home'` to determine if the current page is the home page.\
This is useful when you want to force show the home page elements in a custom layout.
```yaml
---
isHome: true
---
```

@ -439,7 +439,7 @@ export default {
### ignoreDeadLinks ### ignoreDeadLinks
- Type: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` - Type: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- Default: `false` - Default: `false`
When set to `true`, VitePress will not fail builds due to dead links. When set to `true`, VitePress will not fail builds due to dead links.

@ -1,16 +1,18 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const es = defineConfig({ export default defineAdditionalConfig({
lang: 'es-CO', lang: 'es-CO',
description: 'Generador de Sitios Estaticos desarrollado con Vite y Vue.', description: 'Generador de Sitios Estaticos desarrollado con Vite y Vue.',
themeConfig: { themeConfig: {
nav: nav(), nav: nav(),
search: { options: searchOptions() },
sidebar: { sidebar: {
'/es/guide/': { base: '/es/guide/', items: sidebarGuide() }, '/es/guide/': { base: '/es/guide/', items: sidebarGuide() },
'/es/reference/': { base: '/es/reference/', items: sidebarReference() } '/es/reference/': { base: '/es/reference/', items: sidebarReference() }
@ -36,11 +38,15 @@ export const es = defineConfig({
}, },
lastUpdated: { lastUpdated: {
text: 'Actualizado en', text: 'Actualizado en'
formatOptions: { },
dateStyle: 'short',
timeStyle: 'medium' notFound: {
} title: 'PÁGINA NO ENCONTRADA',
quote:
'Pero si no cambias de dirección y sigues buscando, podrías terminar donde te diriges.',
linkLabel: 'ir a inicio',
linkText: 'Llévame a casa'
}, },
langMenuLabel: 'Cambiar Idioma', langMenuLabel: 'Cambiar Idioma',
@ -170,8 +176,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] {
] ]
} }
export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
es: { return {
placeholder: 'Buscar documentos', placeholder: 'Buscar documentos',
translations: { translations: {
button: { button: {
@ -180,10 +186,17 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: 'Limpiar búsqueda', clearButtonTitle: 'Limpiar búsqueda',
resetButtonAriaLabel: 'Limpiar búsqueda', clearButtonAriaLabel: 'Limpiar búsqueda',
cancelButtonText: 'Cancelar', closeButtonText: 'Cerrar',
cancelButtonAriaLabel: 'Cancelar' closeButtonAriaLabel: 'Cerrar',
placeholderText: undefined,
placeholderTextAskAi: undefined,
placeholderTextAskAiStreaming: 'Respondiendo...',
backToKeywordSearchButtonText:
'Volver a la búsqueda por palabras clave',
backToKeywordSearchButtonAriaLabel:
'Volver a la búsqueda por palabras clave'
}, },
startScreen: { startScreen: {
recentSearchesTitle: 'Historial de búsqueda', recentSearchesTitle: 'Historial de búsqueda',
@ -191,24 +204,52 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
saveRecentSearchButtonTitle: 'Guardar en el historial de búsqueda', saveRecentSearchButtonTitle: 'Guardar en el historial de búsqueda',
removeRecentSearchButtonTitle: 'Borrar del historial de búsqueda', removeRecentSearchButtonTitle: 'Borrar del historial de búsqueda',
favoriteSearchesTitle: 'Favoritos', favoriteSearchesTitle: 'Favoritos',
removeFavoriteSearchButtonTitle: 'Borrar de favoritos' removeFavoriteSearchButtonTitle: 'Borrar de favoritos',
recentConversationsTitle: 'Conversaciones recientes',
removeRecentConversationButtonTitle:
'Eliminar esta conversación del historial'
}, },
errorScreen: { errorScreen: {
titleText: 'No fue posible obtener resultados', titleText: 'No fue posible obtener resultados',
helpText: 'Verifique su conexión de red' helpText: 'Verifique su conexión de red'
}, },
footer: {
selectText: 'Seleccionar',
navigateText: 'Navegar',
closeText: 'Cerrar',
searchByText: 'Busqueda por'
},
noResultsScreen: { noResultsScreen: {
noResultsText: 'No fue posible encontrar resultados', noResultsText: 'No fue posible encontrar resultados',
suggestedQueryText: 'Puede intentar una nueva búsqueda', suggestedQueryText: 'Puede intentar una nueva búsqueda',
reportMissingResultsText: reportMissingResultsText:
'Deberian haber resultados para esa consulta?', '¿Deberían haber resultados para esta consulta?',
reportMissingResultsLinkText: 'Click para enviar feedback' reportMissingResultsLinkText: 'Click para enviar feedback'
},
resultsScreen: {
askAiPlaceholder: 'Preguntar a la IA: '
},
askAiScreen: {
disclaimerText:
'Las respuestas son generadas por IA y pueden contener errores. Verifica las respuestas.',
relatedSourcesText: 'Fuentes relacionadas',
thinkingText: 'Pensando...',
copyButtonText: 'Copiar',
copyButtonCopiedText: '¡Copiado!',
copyButtonTitle: 'Copiar',
likeButtonTitle: 'Me gusta',
dislikeButtonTitle: 'No me gusta',
thanksForFeedbackText: '¡Gracias por tu opinión!',
preToolCallText: 'Buscando...',
duringToolCallText: 'Buscando ',
afterToolCallText: 'Búsqueda de',
aggregatedToolCallText: 'Búsqueda de'
},
footer: {
selectText: 'Seleccionar',
submitQuestionText: 'Enviar pregunta',
selectKeyAriaLabel: 'Tecla Enter',
navigateText: 'Navegar',
navigateUpKeyAriaLabel: 'Flecha arriba',
navigateDownKeyAriaLabel: 'Flecha abajo',
closeText: 'Cerrar',
backToSearchText: 'Volver a la búsqueda',
closeKeyAriaLabel: 'Tecla Escape',
poweredByText: 'Búsqueda por'
} }
} }
} }

@ -163,7 +163,7 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # o pnpm / yarn cache: npm # o pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ Si su fuente es un archivo local referenciado via `@font-face`, ella será proce
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// ajuste el regex para corresponder a su fuente // ajuste el regex para corresponder a su fuente
const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -251,6 +251,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )

@ -35,22 +35,6 @@ $ bun add -D vitepress
::: :::
::: details Recibiendo avisos sobre dependencias ausentes?
Si usa PNPM, percibirá un aviso de ausencia de `@docsearch/js`. Esto no evita que VitePress funcione. Si desea eliminar este aviso, adicione lo siguiente en su `package.json`:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip NOTA ::: tip NOTA
VitePress es un paquete apenas para ESM. No use `require()` para importarlo, y asegurese de que el `package.json` más cercano contiene `"type": "module"`, o cambie la extensión de archivo de sus archivos relevantes como `.vitepress/config.js` a `.mjs`/`.mts`. Consulte la [Guía de resolución de problemas Vite](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) para más detalles. Además de eso, dentro de contextos de JavaScript asíncronos, puede usar `await import('vitepress')`. VitePress es un paquete apenas para ESM. No use `require()` para importarlo, y asegurese de que el `package.json` más cercano contiene `"type": "module"`, o cambie la extensión de archivo de sus archivos relevantes como `.vitepress/config.js` a `.mjs`/`.mts`. Consulte la [Guía de resolución de problemas Vite](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) para más detalles. Además de eso, dentro de contextos de JavaScript asíncronos, puede usar `await import('vitepress')`.

@ -256,7 +256,7 @@ La clase `vp-raw` también puede ser usada directamente en elementos. El aislami
} }
``` ```
El utiliza [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) internamente. Puede pasar opciones así: El utiliza [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector) internamente. Puede pasar opciones así:
```js ```js
postcssIsolateStyles({ postcssIsolateStyles({

@ -4,13 +4,13 @@ outline: deep
# Compatibilidad SSR {#ssr-compatibility} # Compatibilidad SSR {#ssr-compatibility}
VitePress pre-interpreta la aplicación en Node.js durante la compilación del producción, utilizando las capacidades de Interpretación del lado del servidor (SSR) de Vue. Esto significa que todo el código personalizado en los componentes del tema está sujeto a la compatibilidad SSR. VitePress pre-renderiza la aplicación en Node.js durante la compilación de producción, utilizando las capacidades de Renderizado del Lado del Servidor (SSR) de Vue. Esto significa que todo el código personalizado en los componentes del tema está sujeto a la Compatibilidad con SSR.
La [sección SSR en la documentación Vue oficial](https://vuejs.org/guide/scaling-up/ssr.html) proporciona más contexto sobre lo que es SSR, la relación entre SSR / SSG y notas comunes sobre escribir código amigable con SSR. La regla general es acceder apenas APIs deln navegador / DOM en los hooks `beforeMount` o `mounted` de los componentes Vue. La [sección SSR en la documentación Vue oficial](https://vuejs.org/guide/scaling-up/ssr.html) proporciona más contexto sobre lo que es SSR, la relación entre SSR / SSG y notas comunes sobre escribir código amigable para SSR. La regla general es acceder a las APIs del navegador / DOM solo en los hooks `beforeMount` o `mounted` de los componentes de Vue.
## `<ClientOnly>` ## `<ClientOnly>`
Se está usando o demostrando componentes que no son compatibles con SSR (por ejemplo, contienen directivas personalizadas), puede envolverlos en el componente embutido `<ClientOnly>`: Si está usando o demostrando componentes que no son compatibles con SSR (por ejemplo, contienen directivas personalizadas), puede envolverlos en el componente incorporado `<ClientOnly>`:
```md ```md
<ClientOnly> <ClientOnly>
@ -20,7 +20,7 @@ Se está usando o demostrando componentes que no son compatibles con SSR (por ej
## Bibliotecas que Acceden el API del Navegador en la Importación {#libraries-that-access-browser-api-on-import} ## Bibliotecas que Acceden el API del Navegador en la Importación {#libraries-that-access-browser-api-on-import}
Algunos componentes o bibliotecas acceden APIs del navegador **en la Importación**. Para usar código que asume un ambiente de navegador en la importación, necesita importarlo dinámicamente. Algunos componentes o librerías acceden a las APIs del navegador **al momento de ser importados**. Para usar código que asume un entorno de navegador en la importación, necesita importarlos dinámicamente.
### Importando en el Hook `mounted` {#importing-in-mounted-hook} ### Importando en el Hook `mounted` {#importing-in-mounted-hook}
@ -29,7 +29,7 @@ Algunos componentes o bibliotecas acceden APIs del navegador **en la Importació
import { onMounted } from 'vue' import { onMounted } from 'vue'
onMounted(() => { onMounted(() => {
import('./lib-que-accede-window-en-la-importacion').then((module) => { import('./lib-que-accede-a-window-en-la-importacion').then((module) => {
// usar código // usar código
}) })
}) })
@ -38,17 +38,17 @@ onMounted(() => {
### Importación Condicional {#conditional-import} ### Importación Condicional {#conditional-import}
Puede también importar condicionalmente usando el flag `import.meta.env.SSR` (parte de las [variables de entorno Vite](https://vitejs.dev/guide/env-and-mode.html#env-variables)): También puede importar una dependencia condicionalmente utilizando la bandera `import.meta.env.SSR` (que forma parte de las [variables de entorno Vite](https://vitejs.dev/guide/env-and-mode.html#env-variables)):
```js ```js
if (!import.meta.env.SSR) { if (!import.meta.env.SSR) {
import('./lib-que-accede-window-en-la-importacion').then((module) => { import('./lib-que-accede-a-window-en-la-importacion').then((module) => {
// usar código // usar código
}) })
} }
``` ```
Como [`Theme.enhanceApp`](./custom-theme#theme-interface) puede ser asíncrono, puede importar condicionalmente y registrar plugins Vue que acceden APIs del navegador en la importación: Dado que [`Theme.enhanceApp`](./custom-theme#theme-interface) puede ser asíncrono, puede importar y registrar condicionalmente plugins de Vue que accedan a las APIs del navegador al ser importados:
```js [.vitepress/theme/index.js] ```js [.vitepress/theme/index.js]
/** @type {import('vitepress').Theme} */ /** @type {import('vitepress').Theme} */
@ -56,7 +56,7 @@ export default {
// ... // ...
async enhanceApp({ app }) { async enhanceApp({ app }) {
if (!import.meta.env.SSR) { if (!import.meta.env.SSR) {
const plugin = await import('plugin-que-accede-window-en-la-importacion') const plugin = await import('plugin-que-accede-a-window-en-la-importacion')
app.use(plugin.default) app.use(plugin.default)
} }
} }
@ -71,7 +71,7 @@ export default {
// ... // ...
async enhanceApp({ app }) { async enhanceApp({ app }) {
if (!import.meta.env.SSR) { if (!import.meta.env.SSR) {
const plugin = await import('plugin-que-accede-window-en-la-importacion') const plugin = await import('plugin-que-accede-a-window-en-la-importacion')
app.use(plugin.default) app.use(plugin.default)
} }
} }
@ -80,14 +80,14 @@ export default {
### `defineClientComponent` ### `defineClientComponent`
VitePress proporciona un auxiliar de conveniencia para importar componentes Vue que acceden APIs del navegador en la importación. VitePress proporciona un auxiliar de conveniencia (helper) para importar componentes Vue que acceden a las APIs del navegador al ser importados.
```vue ```vue
<script setup> <script setup>
import { defineClientComponent } from 'vitepress' import { defineClientComponent } from 'vitepress'
const ClientComp = defineClientComponent(() => { const ClientComp = defineClientComponent(() => {
return import('componente-que-accede-window-en-la-importacion') return import('componente-que-accede-a-window-en-la-importacion')
}) })
</script> </script>
@ -96,7 +96,7 @@ const ClientComp = defineClientComponent(() => {
</template> </template>
``` ```
Puede también pasar propiedades/hijos/_slots_ para el componente objetivo: Puede pasar propiedades/hijos/_slots_ al componente objetivo:
```vue ```vue
<script setup> <script setup>
@ -105,9 +105,9 @@ import { defineClientComponent } from 'vitepress'
const clientCompRef = ref(null) const clientCompRef = ref(null)
const ClientComp = defineClientComponent( const ClientComp = defineClientComponent(
() => import('componente-que-acessa-window-na-importacao'), () => import('componente-que-accede-a-window-en-la-importacion'),
// los argumentos son pasados para h() - https://vuejs.org/api/render-function.html#h // los argumentos se pasan a h() - https://vuejs.org/api/render-function.html#h
[ [
{ {
ref: clientCompRef ref: clientCompRef

@ -12,7 +12,7 @@ Quiere apenas experimentar? Valla al [Início Rápido](./getting-started).
- **Documentación** - **Documentación**
VitePress viene con un tema por defecto proyectado para documentación técnica. El alimenta esta página que está leyendo ahora, juntamente con la documentación [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) e [muchos otros](https://www.vuetelescope.com/explore?framework.slug=vitepress). VitePress viene con un tema por defecto proyectado para documentación técnica. El alimenta esta página que está leyendo ahora, juntamente con la documentación [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) e [muchos otros](https://github.com/search?q=/"vitepress":+/+language:json&type=code).
La [documentación oficial Vue.js](https://vuejs.org/) también está basada en VitePress, pero usa un tema personalizado compartido entre varias traducciones. La [documentación oficial Vue.js](https://vuejs.org/) también está basada en VitePress, pero usa un tema personalizado compartido entre varias traducciones.

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: VitePress
titleTemplate: Generador de Sitios Estáticos desarrollado con Vite y Vue
hero: hero:
name: VitePress name: VitePress
text: Generador de Sitios Estáticos Vite y Vue text: Generador de Sitios Estáticos Vite y Vue

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | Ruta de base pública (por defecto: `/`) (`string`) | | `--base <path>` | Ruta de base pública (por defecto: `/`) (`string`) |
| `--target <target>` | Transpilar objetivo (por defecto: `"modules"`) (`string`) | | `--target <target>` | Transpilar objetivo (por defecto: `"modules"`) (`string`) |
| `--outDir <dir>` | Directorio de salida relativo a **cwd** (por defecto: `<root>/.vitepress/dist`) (`string`) | | `--outDir <dir>` | Directorio de salida relativo a **cwd** (por defecto: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | Habilitar/desabilitar la minificación, o especifica un minero para usar (por defecto: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | Limitar los bytes para alinear los activos en base 64 (por defecto: `4096`) (`number`) | | `--assetsInlineLimit <number>` | Limitar los bytes para alinear los activos en base 64 (por defecto: `4096`) (`number`) |
## `vitepress preview` ## `vitepress preview`

@ -216,16 +216,19 @@ export default defineConfig({
zh: { zh: {
placeholder: '搜索文档', placeholder: '搜索文档',
translations: { translations: {
button: { button: { buttonText: '搜索文档', buttonAriaLabel: '搜索文档' },
buttonText: '搜索文档',
buttonAriaLabel: '搜索文档'
},
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: '清除查询条件', clearButtonTitle: '清除查询条件',
resetButtonAriaLabel: '清除查询条件', clearButtonAriaLabel: '清除查询条件',
cancelButtonText: '取消', closeButtonText: '关闭',
cancelButtonAriaLabel: '取消' closeButtonAriaLabel: '关闭',
placeholderText: '搜索文档',
placeholderTextAskAi: '向 AI 提问:',
placeholderTextAskAiStreaming: '回答中...',
searchInputLabel: '搜索',
backToKeywordSearchButtonText: '返回关键字搜索',
backToKeywordSearchButtonAriaLabel: '返回关键字搜索'
}, },
startScreen: { startScreen: {
recentSearchesTitle: '搜索历史', recentSearchesTitle: '搜索历史',
@ -233,23 +236,46 @@ export default defineConfig({
saveRecentSearchButtonTitle: '保存至搜索历史', saveRecentSearchButtonTitle: '保存至搜索历史',
removeRecentSearchButtonTitle: '从搜索历史中移除', removeRecentSearchButtonTitle: '从搜索历史中移除',
favoriteSearchesTitle: '收藏', favoriteSearchesTitle: '收藏',
removeFavoriteSearchButtonTitle: '从收藏中移除' removeFavoriteSearchButtonTitle: '从收藏中移除',
recentConversationsTitle: '最近的对话',
removeRecentConversationButtonTitle: '从历史记录中删除对话'
}, },
errorScreen: { errorScreen: {
titleText: '无法获取结果', titleText: '无法获取结果',
helpText: '你可能需要检查你的网络连接' helpText: '你可能需要检查你的网络连接'
}, },
footer: {
selectText: '选择',
navigateText: '切换',
closeText: '关闭',
searchByText: '搜索提供者'
},
noResultsScreen: { noResultsScreen: {
noResultsText: '无法找到相关结果', noResultsText: '无法找到相关结果',
suggestedQueryText: '你可以尝试查询', suggestedQueryText: '你可以尝试查询',
reportMissingResultsText: '你认为该查询应该有结果?', reportMissingResultsText: '你认为该查询应该有结果?',
reportMissingResultsLinkText: '点击反馈' reportMissingResultsLinkText: '点击反馈'
},
resultsScreen: { askAiPlaceholder: '向 AI 提问: ' },
askAiScreen: {
disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。',
relatedSourcesText: '相关来源',
thinkingText: '思考中...',
copyButtonText: '复制',
copyButtonCopiedText: '已复制!',
copyButtonTitle: '复制',
likeButtonTitle: '赞',
dislikeButtonTitle: '踩',
thanksForFeedbackText: '感谢你的反馈!',
preToolCallText: '搜索中...',
duringToolCallText: '搜索 ',
afterToolCallText: '已搜索'
},
footer: {
selectText: '选择',
submitQuestionText: '提交问题',
selectKeyAriaLabel: 'Enter 键',
navigateText: '切换',
navigateUpKeyAriaLabel: '向上箭头',
navigateDownKeyAriaLabel: '向下箭头',
closeText: '关闭',
backToSearchText: '返回搜索',
closeKeyAriaLabel: 'Esc 键',
poweredByText: '搜索提供者'
} }
} }
} }
@ -261,6 +287,26 @@ export default defineConfig({
}) })
``` ```
### Algolia Ask AI Support {#ask-ai}
Si deseas incluir **Ask AI**, pasa la opción `askAi` (o alguno de sus campos parciales) dentro de `options`:
```ts
options: {
appId: '...',
apiKey: '...',
indexName: '...',
// askAi: 'TU-ASSISTANT-ID'
askAi: {
assistantId: 'XXXYYY'
}
}
```
::: warning Nota
Si prefieres solo la búsqueda por palabra clave y no la Ask AI, simplemente omite `askAi`.
:::
[Estas opciones](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) se pueden superponer. Consulte la documentación oficial de Algolia para obtener más información sobre ellos. [Estas opciones](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) se pueden superponer. Consulte la documentación oficial de Algolia para obtener más información sobre ellos.
### Configuración _Crawler_ {#crawler-config} ### Configuración _Crawler_ {#crawler-config}

@ -181,36 +181,3 @@ export default {
} }
} }
``` ```
## `useSidebar` <Badge type="info" text="composable" />
Devuelve datos relacionados con la barra lateral. El objeto devuelto tiene el siguiente tipo:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**Exemplo:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">Sólo visible cuando existe la barra lateral</div>
</template>
```

@ -53,12 +53,12 @@ const members = [
Saluda a nuestro increible equipo. Saluda a nuestro increible equipo.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
``` ```
El código anterior mostrará a un miembro del equipo en un elemento similar a una tarjeta. Debería mostrar algo similar a lo siguiente. El código anterior mostrará a un miembro del equipo en un elemento similar a una tarjeta. Debería mostrar algo similar a lo siguiente.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
El componente `<VPTeamMembers>` viene en dos tamaños diferentes, pequeño `small` y médio `medium`. Si bien es una cuestión de preferencia, generalmente el tamaño `small` debería encajar mejor cuando se use en la página del documento. Además, puede agregar más propiedades a cada miembro, como agregar el botón "descripción" o "patrocinador". Obtenga más información sobre en [`<VPTeamMembers>`](#vpteammembers). El componente `<VPTeamMembers>` viene en dos tamaños diferentes, pequeño `small` y médio `medium`. Si bien es una cuestión de preferencia, generalmente el tamaño `small` debería encajar mejor cuando se use en la página del documento. Además, puede agregar más propiedades a cada miembro, como agregar el botón "descripción" o "patrocinador". Obtenga más información sobre en [`<VPTeamMembers>`](#vpteammembers).
@ -107,9 +107,7 @@ const members = [
Algunos de los miembros han elegido aparecer a continuación. Algunos de los miembros han elegido aparecer a continuación.
</template> </template>
</VPTeamPageTitle> </VPTeamPageTitle>
<VPTeamMembers <VPTeamMembers :members />
:members="members"
/>
</VPTeamPage> </VPTeamPage>
``` ```

@ -439,7 +439,7 @@ export default {
### ignoreDeadLinks ### ignoreDeadLinks
- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` - Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- Predeterminado: `false` - Predeterminado: `false`
Cuando se establece en `true`, VitePress no dejará de compilarse debido a links rotos. Cuando se establece en `true`, VitePress no dejará de compilarse debido a links rotos.

@ -1,25 +1,26 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const fa = defineConfig({ export default defineAdditionalConfig({
title: 'ویت‌پرس',
lang: 'fa-IR', lang: 'fa-IR',
description: 'Vite & Vue powered static site generator.', description: 'ژنراتور استاتیک وب‌سایت با Vite و Vue',
dir: 'rtl', dir: 'rtl',
markdown: {
container: { // prettier-ignore
tipLabel: 'نکته', head: [
warningLabel: 'هشدار', ['link', { rel: 'preconnect', href: 'https://fonts.googleapis.com' }],
dangerLabel: 'خطر', ['link', { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }],
infoLabel: 'اطلاعات', ['link', { href: 'https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100..900&display=swap', rel: 'stylesheet' }],
detailsLabel: 'جزئیات' ],
}
},
themeConfig: { themeConfig: {
nav: nav(), nav: nav(),
search: { options: searchOptions() },
sidebar: { sidebar: {
'/fa/guide/': { base: '/fa/guide/', items: sidebarGuide() }, '/fa/guide/': { base: '/fa/guide/', items: sidebarGuide() },
'/fa/reference/': { base: '/fa/reference/', items: sidebarReference() } '/fa/reference/': { base: '/fa/reference/', items: sidebarReference() }
@ -45,11 +46,15 @@ export const fa = defineConfig({
}, },
lastUpdated: { lastUpdated: {
text: 'آخرین به‌روزرسانی‌', text: 'آخرین به‌روزرسانی‌'
formatOptions: { },
dateStyle: 'short',
timeStyle: 'medium' notFound: {
} title: 'صفحه پیدا نشد',
quote:
'اما اگر جهت خود را تغییر ندهید و همچنان به جستجو ادامه دهید، ممکن است در نهایت به جایی برسید که در حال رفتن به آن هستید.',
linkLabel: 'برو به خانه',
linkText: 'من را به خانه ببر'
}, },
langMenuLabel: 'تغییر زبان', langMenuLabel: 'تغییر زبان',
@ -58,14 +63,6 @@ export const fa = defineConfig({
darkModeSwitchLabel: 'تم تاریک', darkModeSwitchLabel: 'تم تاریک',
lightModeSwitchTitle: 'رفتن به حالت روشن', lightModeSwitchTitle: 'رفتن به حالت روشن',
darkModeSwitchTitle: 'رفتن به حالت تاریک', darkModeSwitchTitle: 'رفتن به حالت تاریک',
notFound: {
linkLabel: 'بازگشت به خانه',
linkText: 'بازگشت به خانه',
title: 'صفحه مورد نظر یافت نشد',
code: '۴۰۴',
quote:
'اما اگر جهت خود را تغییر ندهید و اگر ادامه دهید به دنبال چیزی که دنبال می‌کنید، ممکن است در نهایت به جایی که در حال رفتن به سمتش هستید، برسید.'
},
siteTitle: 'ویت‌پرس' siteTitle: 'ویت‌پرس'
} }
}) })
@ -181,8 +178,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] {
] ]
} }
export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
fa: { return {
placeholder: 'جستجوی مستندات', placeholder: 'جستجوی مستندات',
translations: { translations: {
button: { button: {
@ -191,31 +188,67 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: 'آغاز مجدد جستجو', clearButtonTitle: 'پاک کردن جستجو',
resetButtonAriaLabel: 'آغاز مجدد جستجو', clearButtonAriaLabel: 'پاک کردن جستجو',
cancelButtonText: 'لغو', closeButtonText: 'بستن',
cancelButtonAriaLabel: 'لغو' closeButtonAriaLabel: 'بستن',
placeholderText: 'جستجوی مستندات',
placeholderTextAskAi: 'از هوش مصنوعی بپرسید: ',
placeholderTextAskAiStreaming: 'در حال پاسخ...',
searchInputLabel: 'جستجو',
backToKeywordSearchButtonText: 'بازگشت به جستجوی کلیدواژه',
backToKeywordSearchButtonAriaLabel: 'بازگشت به جستجوی کلیدواژه'
}, },
startScreen: { startScreen: {
recentSearchesTitle: 'جستجو‌های اخیر', recentSearchesTitle: 'جستجوهای اخیر',
noRecentSearchesText: 'تاریخچه جستجویی یافت نشد.', noRecentSearchesText: 'هیچ جستجوی اخیر',
saveRecentSearchButtonTitle: 'ذخیره تاریخچه جستجو', saveRecentSearchButtonTitle: 'ذخیره در تاریخچه جستجو',
removeRecentSearchButtonTitle: 'حذف تاریخچه جستجو', removeRecentSearchButtonTitle: 'حذف از تاریخچه جستجو',
favoriteSearchesTitle: 'موارد دلخواه', favoriteSearchesTitle: 'علاقه‌مندی‌ها',
removeFavoriteSearchButtonTitle: 'حذف مورد دلخواه' removeFavoriteSearchButtonTitle: 'حذف از علاقه‌مندی‌ها',
recentConversationsTitle: 'گفتگوهای اخیر',
removeRecentConversationButtonTitle: 'حذف این گفتگو از تاریخچه'
}, },
errorScreen: { errorScreen: {
titleText: 'نتیجه‌ای یافت نشد برای', titleText: 'عدم امکان دریافت نتایج',
helpText: 'اتصال شبکه خود را بررسی کنید' helpText: 'اتصال شبکه خود را بررسی کنید'
}, },
noResultsScreen: {
noResultsText: 'هیچ نتیجه‌ای یافت نشد',
suggestedQueryText: 'می‌توانید جستجوی دیگری امتحان کنید',
reportMissingResultsText: 'فکر می‌کنید باید نتیجه‌ای نمایش داده شود؟',
reportMissingResultsLinkText: 'برای ارسال بازخورد کلیک کنید'
},
resultsScreen: {
askAiPlaceholder: 'از هوش مصنوعی بپرسید: '
},
askAiScreen: {
disclaimerText:
'پاسخ‌ها توسط هوش مصنوعی تولید می‌شوند و ممکن است خطا داشته باشند. لطفاً بررسی کنید.',
relatedSourcesText: 'منابع مرتبط',
thinkingText: 'در حال پردازش...',
copyButtonText: 'کپی',
copyButtonCopiedText: 'کپی شد!',
copyButtonTitle: 'کپی',
likeButtonTitle: 'پسندیدم',
dislikeButtonTitle: 'نپسندیدم',
thanksForFeedbackText: 'از بازخورد شما سپاسگزاریم!',
preToolCallText: 'در حال جستجو...',
duringToolCallText: 'در حال جستجو برای ',
afterToolCallText: 'جستجو انجام شد',
aggregatedToolCallText: 'جستجو انجام شد'
},
footer: { footer: {
selectText: 'انتخاب', selectText: 'انتخاب',
navigateText: 'رفتن', submitQuestionText: 'ارسال پرسش',
selectKeyAriaLabel: 'کلید Enter',
navigateText: 'حرکت',
navigateUpKeyAriaLabel: 'کلید جهت بالا',
navigateDownKeyAriaLabel: 'کلید جهت پایین',
closeText: 'بستن', closeText: 'بستن',
searchByText: ' جستجو با ' backToSearchText: 'بازگشت به جستجو',
}, closeKeyAriaLabel: 'کلید Escape',
noResultsScreen: { poweredByText: 'جستجو توسط'
noResultsText: 'نتیجه‌ای یافت نشد برای'
} }
} }
} }

@ -161,7 +161,7 @@ Cache-Control: max-age=31536000,immutable
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # or pnpm / yarn cache: npm # or pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ export default DefaultTheme
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// منظور شده برای همسان سازی font خود، regex مورد نیاز را تنظیم کنید // منظور شده برای همسان سازی font خود، regex مورد نیاز را تنظیم کنید
const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -254,6 +254,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )

@ -39,23 +39,6 @@ $ bun add -D vitepress
::: :::
::: details درباره peer dependency های ناموجود هشدار دریافت می‌کنید؟
اگر از PNPM استفاده می‌کنید، متوجه هشدار peer dependency برای `@docsearch/js` خواهید شد. این مسئله جلوی عملکرد ویت‌پرس را نمی‌گیرد. اگر می‌خواهید این هشدار را نادیده بگیرید، موارد زیر را به `package.json` خود اضافه کنید:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip نکته ::: tip نکته
ویت‌پرس یک بسته فقط ESM است. از `require()` برای وارد کردن آن استفاده نکنید و اطمینان حاصل کنید که نزدیک‌ترین `package.json` شما شامل `"type": "module"` است، یا پسوند فایل‌های مربوطه خود مانند `.vitepress/config.js` را به `.mjs`/`.mts` تغییر دهید. برای جزئیات بیشتر به [راهنمای عیب‌یابی Vite](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) مراجعه کنید. همچنین، در زمینه‌های async CJS می‌توانید از `await import('vitepress')` استفاده کنید. ویت‌پرس یک بسته فقط ESM است. از `require()` برای وارد کردن آن استفاده نکنید و اطمینان حاصل کنید که نزدیک‌ترین `package.json` شما شامل `"type": "module"` است، یا پسوند فایل‌های مربوطه خود مانند `.vitepress/config.js` را به `.mjs`/`.mts` تغییر دهید. برای جزئیات بیشتر به [راهنمای عیب‌یابی Vite](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) مراجعه کنید. همچنین، در زمینه‌های async CJS می‌توانید از `await import('vitepress')` استفاده کنید.

@ -255,7 +255,7 @@ export default defineConfig({
} }
``` ```
این از [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) استفاده می‌کند. می‌توانید گزینه‌های آن را به این صورت پاس بدهید: این از [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector) استفاده می‌کند. می‌توانید گزینه‌های آن را به این صورت پاس بدهید:
```js ```js
postcssIsolateStyles({ postcssIsolateStyles({

@ -12,7 +12,7 @@
- **مستندسازی** - **مستندسازی**
ویت‌پرس با یک تم پیش‌فرض طراحی شده برای مستندات فنی ارائه می‌شود. این صفحه‌ای که اکنون در حال خواندن آن هستید و همچنین مستندات [Vite](https://vitejs.dev/)، [Rollup](https://rollupjs.org/)، [Pinia](https://pinia.vuejs.org/)، [VueUse](https://vueuse.org/)، [Vitest](https://vitest.dev/)، [D3](https://d3js.org/)، [UnoCSS](https://unocss.dev/)، [Iconify](https://iconify.design/) و [بسیاری دیگر](https://www.vuetelescope.com/explore?framework.slug=vitepress) با استفاده از ویت‌پرس ساخته شده‌اند. ویت‌پرس با یک تم پیش‌فرض طراحی شده برای مستندات فنی ارائه می‌شود. این صفحه‌ای که اکنون در حال خواندن آن هستید و همچنین مستندات [Vite](https://vitejs.dev/)، [Rollup](https://rollupjs.org/)، [Pinia](https://pinia.vuejs.org/)، [VueUse](https://vueuse.org/)، [Vitest](https://vitest.dev/)، [D3](https://d3js.org/)، [UnoCSS](https://unocss.dev/)، [Iconify](https://iconify.design/) و [بسیاری دیگر](https://github.com/search?q=/"vitepress":+/+language:json&type=code) با استفاده از ویت‌پرس ساخته شده‌اند.
[مستندات رسمی Vue.js](https://vuejs.org/) نیز بر پایه ویت‌پرس ساخته شده است، اما از یک تم سفارشی که بین چندین ترجمه مشترک است استفاده می‌کند. [مستندات رسمی Vue.js](https://vuejs.org/) نیز بر پایه ویت‌پرس ساخته شده است، اما از یک تم سفارشی که بین چندین ترجمه مشترک است استفاده می‌کند.

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: ویت‌پرس
titleTemplate: Vite & Vue Powered Static Site Generator
hero: hero:
name: ویت‌پرس name: ویت‌پرس
text: سازنده سایت‌های ایستا به کمک Vite و Vue text: سازنده سایت‌های ایستا به کمک Vite و Vue

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | مسیر پایه عمومی (پیش‌فرض: `/`) (`string`) | | `--base <path>` | مسیر پایه عمومی (پیش‌فرض: `/`) (`string`) |
| `--target <target>` | هدف ترنسپایل (پیش‌فرض: `"modules"`) (`string`) | | `--target <target>` | هدف ترنسپایل (پیش‌فرض: `"modules"`) (`string`) |
| `--outDir <dir>` | دایرکتوری خروجی نسبت به **cwd** (پیش‌فرض: `<root>/.vitepress/dist`) (`string`) | | `--outDir <dir>` | دایرکتوری خروجی نسبت به **cwd** (پیش‌فرض: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | فعال یا غیرفعال کردن فشرده‌سازی، یا تعیین فشرده‌سازی برای استفاده (پیش‌فرض: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | آستانه تبدیل پایه ۶۴ استاتیک به بایت (پیش‌فرض: `4096`) (`number`) | | `--assetsInlineLimit <number>` | آستانه تبدیل پایه ۶۴ استاتیک به بایت (پیش‌فرض: `4096`) (`number`) |
## `vitepress preview` {#vitepress-preview} ## `vitepress preview` {#vitepress-preview}

@ -212,9 +212,7 @@ export default defineConfig({
import { defineConfig } from 'vitepress' import { defineConfig } from 'vitepress'
export default defineConfig({ export default defineConfig({
themeConfig: themeConfig: {
{
search: { search: {
provider: 'algolia', provider: 'algolia',
options: { options: {
@ -223,40 +221,40 @@ export default defineConfig({
indexName: '...', indexName: '...',
locales: { locales: {
zh: { zh: {
placeholder: 'جستجو در مستندات', placeholder: '搜索文档',
translations: { translations: {
button: { button: {
buttonText: 'جستجو در مستندات', buttonText: '搜索文档',
buttonAriaLabel: 'جستجو در مستندات' buttonAriaLabel: '搜索文档'
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: 'پاک کردن شرایط جستجو', resetButtonTitle: '清除搜索条件',
resetButtonAriaLabel: 'پاک کردن شرایط جستجو', resetButtonAriaLabel: '清除搜索条件',
cancelButtonText: 'لغو', cancelButtonText: '取消',
cancelButtonAriaLabel: 'لغو' cancelButtonAriaLabel: '取消'
}, },
startScreen: { startScreen: {
recentSearchesTitle: 'تاریخچه جستجو', recentSearchesTitle: '最近搜索',
noRecentSearchesText: 'هیچ تاریخچه جستجویی وجود ندارد', noRecentSearchesText: '没有最近搜索',
saveRecentSearchButtonTitle: 'ذخیره در تاریخچه جستجو', saveRecentSearchButtonTitle: '保存到最近搜索',
removeRecentSearchButtonTitle: 'حذف از تاریخچه جستجو' removeRecentSearchButtonTitle: '从最近搜索中删除'
}, },
errorScreen: { errorScreen: {
titleText: 'نمایش نتایج امکان‌پذیر نیست', titleText: '无法显示结果',
helpText: 'شما ممکن است نیاز به بررسی اتصال اینترنت خود داشته باشید' helpText: '您可能需要检查您的互联网连接'
}, },
footer: { footer: {
selectText: 'انتخاب', selectText: '选择',
navigateText: 'جابجایی', navigateText: '导航',
closeText: 'بستن', closeText: '关闭',
searchByText: 'جستجو توسط' searchByText: '搜索由'
}, },
noResultsScreen: { noResultsScreen: {
noResultsText: 'نتیجه‌ای پیدا نشد', noResultsText: '没有找到结果',
suggestedQueryText: 'می‌توانید امتحان کنید', suggestedQueryText: '您可以尝试',
reportMissingResultsText: 'فکر می‌کنید باید نتایجی وجود داشته باشد؟', reportMissingResultsText: '您认为应该有结果吗?',
reportMissingResultsLinkText: 'برای بازخورد کلیک کنید' reportMissingResultsLinkText: '点击这里报告'
} }
} }
} }
@ -377,3 +375,22 @@ new Crawler({
} }
}) })
``` ```
### پشتیبانی Algolia Ask AI {#ask-ai}
برای فعال‌سازی **Ask AI** کافی است گزینه `askAi` را اضافه کنید:
```ts
options: {
appId: '...',
apiKey: '...',
indexName: '...',
askAi: {
assistantId: 'XXXYYY'
}
}
```
::: warning نکته
اگر فقط به جستجوی کلمات کلیدی نیاز دارید، `askAi` را اضافه نکنید.
:::

@ -178,38 +178,3 @@ export default {
} }
} }
``` ```
## `useSidebar` <Badge type="info" text="composable" /> {#usesidebar}
داده‌های مربوط به نوار کناری را برمی‌گرداند. شیء برگردانده شده دارای نوع‌های زیر است:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**مثال:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">فقط ن
مایش داده شود زمانی که نوار کناری وجود دارد</div>
</template>
```

@ -53,12 +53,12 @@ const members = [
با سلام به تیم فوق‌العاده‌ی ما خوش آمدید. با سلام به تیم فوق‌العاده‌ی ما خوش آمدید.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
``` ```
بالا به صورت عنصری با شکل کارتی اعضای تیم را نمایش می‌دهد. باید به شکل زیر نمایش داده شود. بالا به صورت عنصری با شکل کارتی اعضای تیم را نمایش می‌دهد. باید به شکل زیر نمایش داده شود.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
کامپوننت `<VPTeamMembers>` دارای دو اندازه مختلف، `small` و `medium` است. معمولاً اندازه `small` برای استفاده در صفحات مستندات مناسب‌تر است. همچنین می‌توانید ویژگی‌های بیشتری برای هر عضو اضافه کنید مانند "توضیحات" یا "دکمه حامی". جهت کسب اطلاعات بیشتر به [`<VPTeamMembers>`](#vpteammembers) مراجعه کنید. کامپوننت `<VPTeamMembers>` دارای دو اندازه مختلف، `small` و `medium` است. معمولاً اندازه `small` برای استفاده در صفحات مستندات مناسب‌تر است. همچنین می‌توانید ویژگی‌های بیشتری برای هر عضو اضافه کنید مانند "توضیحات" یا "دکمه حامی". جهت کسب اطلاعات بیشتر به [`<VPTeamMembers>`](#vpteammembers) مراجعه کنید.
@ -106,9 +106,7 @@ const members = [
توسعه ویت‌پرس توسط تیمی بین‌المللی راهنمایی می‌شود، برخی از اعضا که انتخاب کرده‌اند تا در زیر نمایش داده شوند. توسعه ویت‌پرس توسط تیمی بین‌المللی راهنمایی می‌شود، برخی از اعضا که انتخاب کرده‌اند تا در زیر نمایش داده شوند.
</template> </template>
</VPTeamPageTitle> </VPTeamPageTitle>
<VPTeamMembers <VPTeamMembers :members />
:members="members"
/>
</VPTeamPage> </VPTeamPage>
``` ```

@ -441,7 +441,7 @@ export default {
### ignoreDeadLinks ### ignoreDeadLinks
- نوع: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` - نوع: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- پیش‌فرض: `false` - پیش‌فرض: `false`
زمانی که به `true` تنظیم شود، ویت‌پرس به دلیل لینک‌های مرده ساخت‌ها را شکست نخواهد داد. زمانی که به `true` تنظیم شود، ویت‌پرس به دلیل لینک‌های مرده ساخت‌ها را شکست نخواهد داد.

@ -1,16 +1,18 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const ko = defineConfig({ export default defineAdditionalConfig({
lang: 'ko-KR', lang: 'ko-KR',
description: 'Vite 및 Vue 기반 정적 사이트 생성기.', description: 'Vite 및 Vue 기반 정적 사이트 생성기.',
themeConfig: { themeConfig: {
nav: nav(), nav: nav(),
search: { options: searchOptions() },
sidebar: { sidebar: {
'/ko/guide/': { base: '/ko/guide/', items: sidebarGuide() }, '/ko/guide/': { base: '/ko/guide/', items: sidebarGuide() },
'/ko/reference/': { base: '/ko/reference/', items: sidebarReference() } '/ko/reference/': { base: '/ko/reference/', items: sidebarReference() }
@ -39,6 +41,14 @@ export const ko = defineConfig({
text: '업데이트 날짜' text: '업데이트 날짜'
}, },
notFound: {
title: '페이지를 찾을 수 없습니다',
quote:
'방향을 바꾸지 않고 계속 찾다 보면 결국 당신이 가고 있는 곳에 도달할 수도 있습니다.',
linkLabel: '홈으로 가기',
linkText: '집으로 데려가줘'
},
langMenuLabel: '언어 변경', langMenuLabel: '언어 변경',
returnToTopLabel: '맨 위로 돌아가기', returnToTopLabel: '맨 위로 돌아가기',
sidebarMenuLabel: '사이드바 메뉴', sidebarMenuLabel: '사이드바 메뉴',
@ -208,8 +218,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] {
] ]
} }
export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
ko: { return {
placeholder: '문서 검색', placeholder: '문서 검색',
translations: { translations: {
button: { button: {
@ -218,10 +228,16 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: '검색 지우기', clearButtonTitle: '검색 지우기',
resetButtonAriaLabel: '검색 지우기', clearButtonAriaLabel: '검색 지우기',
cancelButtonText: '취소', closeButtonText: '닫기',
cancelButtonAriaLabel: '취소' closeButtonAriaLabel: '닫기',
placeholderText: '문서 검색',
placeholderTextAskAi: 'AI에게 물어보기: ',
placeholderTextAskAiStreaming: '답변 작성 중...',
searchInputLabel: '검색',
backToKeywordSearchButtonText: '키워드 검색으로 돌아가기',
backToKeywordSearchButtonAriaLabel: '키워드 검색으로 돌아가기'
}, },
startScreen: { startScreen: {
recentSearchesTitle: '검색 기록', recentSearchesTitle: '검색 기록',
@ -229,23 +245,50 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
saveRecentSearchButtonTitle: '검색 기록에 저장', saveRecentSearchButtonTitle: '검색 기록에 저장',
removeRecentSearchButtonTitle: '검색 기록에서 삭제', removeRecentSearchButtonTitle: '검색 기록에서 삭제',
favoriteSearchesTitle: '즐겨찾기', favoriteSearchesTitle: '즐겨찾기',
removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제' removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제',
recentConversationsTitle: '최근 대화',
removeRecentConversationButtonTitle: '대화를 기록에서 삭제'
}, },
errorScreen: { errorScreen: {
titleText: '결과를 가져올 수 없습니다', titleText: '결과를 가져올 수 없습니다',
helpText: '네트워크 연결을 확인하세요' helpText: '네트워크 연결을 확인하세요'
}, },
noResultsScreen: {
noResultsText: '결과를 찾을 수 없습니다',
suggestedQueryText: '다른 검색어를 시도해 보세요',
reportMissingResultsText: '결과가 있어야 한다고 생각하나요?',
reportMissingResultsLinkText: '피드백 보내기'
},
resultsScreen: {
askAiPlaceholder: 'AI에게 물어보기: '
},
askAiScreen: {
disclaimerText:
'AI가 생성한 답변으로 오류가 있을 수 있습니다. 반드시 확인하세요.',
relatedSourcesText: '관련 소스',
thinkingText: '생각 중...',
copyButtonText: '복사',
copyButtonCopiedText: '복사됨!',
copyButtonTitle: '복사',
likeButtonTitle: '좋아요',
dislikeButtonTitle: '싫어요',
thanksForFeedbackText: '피드백 감사합니다!',
preToolCallText: '검색 중...',
duringToolCallText: '검색 중 ',
afterToolCallText: '검색 완료',
aggregatedToolCallText: '검색 완료'
},
footer: { footer: {
selectText: '선택', selectText: '선택',
submitQuestionText: '질문 보내기',
selectKeyAriaLabel: 'Enter 키',
navigateText: '탐색', navigateText: '탐색',
navigateUpKeyAriaLabel: '위쪽 화살표',
navigateDownKeyAriaLabel: '아래쪽 화살표',
closeText: '닫기', closeText: '닫기',
searchByText: '검색 기준' backToSearchText: '검색으로 돌아가기',
}, closeKeyAriaLabel: 'Esc 키',
noResultsScreen: { poweredByText: '제공: '
noResultsText: '결과를 찾을 수 없습니다',
suggestedQueryText: '새로운 검색을 시도할 수 있습니다',
reportMissingResultsText: '해당 검색어에 대한 결과가 있어야 합니까?',
reportMissingResultsLinkText: '피드백 보내기 클릭'
} }
} }
} }

@ -162,7 +162,7 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # 또는 pnpm / yarn cache: npm # 또는 pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ export default DefaultTheme
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// 폰트를 매칭하기 위해 정규식을 적절히 조정하세요 // 폰트를 매칭하기 위해 정규식을 적절히 조정하세요
const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -252,6 +252,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )

@ -40,22 +40,6 @@ $ bun add -D vitepress
::: :::
::: details "missing peer deps" 경고가 표시되나요?
PNPM을 사용하는 경우 `@docsearch/js`에 대한 "missing peer deps" 경고가 표시됩니다. 이는 VitePress가 작동하는 것을 방해하지 않습니다. 이 경고를 억제하려면 `package.json`에 다음을 추가합니다:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip 참고 ::: tip 참고
VitePress는 ESM 전용 패키지입니다. `require()`를 사용하여 가져오지 마시고, `package.json``"type": "module"`이 포함되어 있는지 확인하거나, 관련 파일(예: `.vitepress/config.js`)의 확장자를 `.mjs`/`.mts`로 변경하세요. 자세한 내용은 [Vite 문제 해결 가이드](http://vitejs.dev/ko/guide/troubleshooting.html#this-package-is-esm-only)를 참고하세요. 또한, 비동기 CJS 컨텍스트에서는 `await import('vitepress')`를 사용할 수 있습니다. VitePress는 ESM 전용 패키지입니다. `require()`를 사용하여 가져오지 마시고, `package.json``"type": "module"`이 포함되어 있는지 확인하거나, 관련 파일(예: `.vitepress/config.js`)의 확장자를 `.mjs`/`.mts`로 변경하세요. 자세한 내용은 [Vite 문제 해결 가이드](http://vitejs.dev/ko/guide/troubleshooting.html#this-package-is-esm-only)를 참고하세요. 또한, 비동기 CJS 컨텍스트에서는 `await import('vitepress')`를 사용할 수 있습니다.

@ -125,7 +125,7 @@ import CustomComponent from '../components/CustomComponent.vue'
컴포넌트가 대부분의 페이지에서 사용될 경우, Vue 앱 인스턴스를 커스텀하여 전역적으로 등록할 수 있습니다. [기본 테마 확장](./extending-default-theme#registering-global-components)의 관련 섹션을 예제를 참고하세요. 컴포넌트가 대부분의 페이지에서 사용될 경우, Vue 앱 인스턴스를 커스텀하여 전역적으로 등록할 수 있습니다. [기본 테마 확장](./extending-default-theme#registering-global-components)의 관련 섹션을 예제를 참고하세요.
::: warning 중요 ::: warning 중요
커스텀 컴포넌트의 이름에 하이픈이 포함되어 있거나 파스칼케이스(PascalCase)e인지 확인하세요. 그렇지 않으면 인라인 요소로 처리되어 `<p>` 태그 안에 래핑됩니다. `<p>`는 블록 엘리먼트를 내부에 배치할 수 없기 때문에 하이드레이션 불일치가 발생합니다. 커스텀 컴포넌트의 이름에 하이픈이 포함되어 있거나 파스칼케이스(PascalCase)인지 확인하세요. 그렇지 않으면 인라인 요소로 처리되어 `<p>` 태그 안에 래핑됩니다. `<p>`는 블록 엘리먼트를 내부에 배치할 수 없기 때문에 하이드레이션 불일치가 발생합니다.
::: :::
### 헤더에 <ComponentInHeader /> 컴포넌트 사용하기 {#using-components-in-headers} ### 헤더에 <ComponentInHeader /> 컴포넌트 사용하기 {#using-components-in-headers}

@ -12,7 +12,7 @@ VitePress는 빠르고 컨텐츠 중심의 웹사이트를 구축하기 위해
- **문서화** - **문서화**
VitePress는 기술 문서를 위해 설계된 기본 테마가 함께 제공됩니다. 지금 읽고 있는 이 페이지와 [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) 및 [다양한 프로젝트](https://www.vuetelescope.com/explore?framework.slug=vitepress) 문서는 모두 이 테마를 기반으로 합니다. VitePress는 기술 문서를 위해 설계된 기본 테마가 함께 제공됩니다. 지금 읽고 있는 이 페이지와 [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) 및 [다양한 프로젝트](https://github.com/search?q=/"vitepress":+/+language:json&type=code) 문서는 모두 이 테마를 기반으로 합니다.
[Vue.js 공식 문서](https://vuejs.org/)도 VitePress 기반으로 되어 있으며, 여러 번역본에 걸쳐 공유되는 커스텀 테마를 사용합니다. [Vue.js 공식 문서](https://vuejs.org/)도 VitePress 기반으로 되어 있으며, 여러 번역본에 걸쳐 공유되는 커스텀 테마를 사용합니다.

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: VitePress
titleTemplate: Vite & Vue 기반 정적 사이트 생성기
hero: hero:
name: VitePress name: VitePress
text: Vite & Vue 기반 정적 사이트 생성기 text: Vite & Vue 기반 정적 사이트 생성기

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | Public 기본 경로 (기본값: `/`) (`string`) | | `--base <path>` | Public 기본 경로 (기본값: `/`) (`string`) |
| `--target <target>` | 트랜스파일 대상 (기본값: `"modules"`) (`string`) | | `--target <target>` | 트랜스파일 대상 (기본값: `"modules"`) (`string`) |
| `--outDir <dir>` | **cwd** 기준 출력 디렉터리 (기본값: `<root>/.vitepress/dist`) (`string`) | | `--outDir <dir>` | **cwd** 기준 출력 디렉터리 (기본값: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | minify 활성화/비활성화 또는 사용할 minify 도구 지정 (기본값: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>`| 바이트 단위의 정적 에셋 base64 인라인 임계값 (기본값: `4096`) (`number`) | | `--assetsInlineLimit <number>`| 바이트 단위의 정적 에셋 base64 인라인 임계값 (기본값: `4096`) (`number`) |
## `vitepress preview` ## `vitepress preview`

@ -377,3 +377,20 @@ new Crawler({
} }
}) })
``` ```
### Algolia Ask AI 지원 {#ask-ai}
**Ask AI** 기능을 사용하려면 `askAi` 옵션을 추가하세요:
```ts
options: {
appId: '...',
apiKey: '...',
indexName: '...',
askAi: { assistantId: 'XXXYYY' }
}
```
::: warning 참고
Ask AI를 사용하지 않으려면 `askAi` 옵션을 생략하면 됩니다.
:::

@ -180,36 +180,3 @@ export default {
} }
} }
``` ```
## `useSidebar` <Badge type="info" text="composable" />
사이드바 관련 데이터를 반환합니다. 반환된 객체는 다음과 같은 타입을 가집니다:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**예제:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">사이드바가 있을 때만 보여줍니다</div>
</template>
```

@ -53,12 +53,12 @@ const members = [
Say hello to our awesome team. Say hello to our awesome team.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
``` ```
위 코드는 카드 형태의 엘리먼트로 팀 구성원을 표시합니다. 아래와 비슷한 형태로 표시됩니다. 위 코드는 카드 형태의 엘리먼트로 팀 구성원을 표시합니다. 아래와 비슷한 형태로 표시됩니다.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
`<VPTeamMembers>` 컴포넌트는 `small``medium` 두 가지 크기로 제공됩니다. 개인의 선호도에 따라 선택할 수 있지만, 일반적으로 `small` 사이즈가 문서 페이지에 더 적합합니다. 또한, 각 구성원에 "설명"이나 "후원" 버튼과 같은 프로퍼티를 추가할 수도 있습니다. 자세한 내용은 [`<VPTeamMembers>`](#vpteammembers)에서 확인할 수 있습니다. `<VPTeamMembers>` 컴포넌트는 `small``medium` 두 가지 크기로 제공됩니다. 개인의 선호도에 따라 선택할 수 있지만, 일반적으로 `small` 사이즈가 문서 페이지에 더 적합합니다. 또한, 각 구성원에 "설명"이나 "후원" 버튼과 같은 프로퍼티를 추가할 수도 있습니다. 자세한 내용은 [`<VPTeamMembers>`](#vpteammembers)에서 확인할 수 있습니다.
@ -107,9 +107,7 @@ const members = [
team, some of whom have chosen to be featured below. team, some of whom have chosen to be featured below.
</template> </template>
</VPTeamPageTitle> </VPTeamPageTitle>
<VPTeamMembers <VPTeamMembers :members />
:members="members"
/>
</VPTeamPage> </VPTeamPage>
``` ```

@ -439,7 +439,7 @@ export default {
### ignoreDeadLinks ### ignoreDeadLinks
- 타입: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` - 타입: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- 기본값: `false` - 기본값: `false`
`true`로 설정하면, 빌드 시 죽은 링크로 인해 실패하지 않습니다. `true`로 설정하면, 빌드 시 죽은 링크로 인해 실패하지 않습니다.

@ -6,8 +6,8 @@
}, },
"files": [ "files": [
{ {
"location": ".vitepress/config/{en,zh,pt,ru,es,ko,fa}.ts", "location": "**/config.ts",
"pattern": ".vitepress/config/@lang.ts", "pattern": "@lang/@path",
"type": "universal" "type": "universal"
}, },
{ {

@ -13,8 +13,9 @@
"@lunariajs/core": "^0.1.1", "@lunariajs/core": "^0.1.1",
"markdown-it-mathjax3": "^4.3.2", "markdown-it-mathjax3": "^4.3.2",
"open-cli": "^8.0.0", "open-cli": "^8.0.0",
"postcss-rtlcss": "^5.6.0", "postcss-rtlcss": "^5.7.1",
"vitepress": "workspace:*", "vitepress": "workspace:*",
"vitepress-plugin-group-icons": "^1.3.6" "vitepress-plugin-group-icons": "^1.6.1",
"vitepress-plugin-llms": "^1.7.1"
} }
} }

@ -1,16 +1,18 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const pt = defineConfig({ export default defineAdditionalConfig({
lang: 'pt-BR', lang: 'pt-BR',
description: 'Gerador de Site Estático desenvolvido com Vite e Vue.', description: 'Gerador de Site Estático desenvolvido com Vite e Vue.',
themeConfig: { themeConfig: {
nav: nav(), nav: nav(),
search: { options: searchOptions() },
sidebar: { sidebar: {
'/pt/guide/': { base: '/pt/guide/', items: sidebarGuide() }, '/pt/guide/': { base: '/pt/guide/', items: sidebarGuide() },
'/pt/reference/': { base: '/pt/reference/', items: sidebarReference() } '/pt/reference/': { base: '/pt/reference/', items: sidebarReference() }
@ -36,11 +38,15 @@ export const pt = defineConfig({
}, },
lastUpdated: { lastUpdated: {
text: 'Atualizado em', text: 'Atualizado em'
formatOptions: { },
dateStyle: 'short',
timeStyle: 'medium' notFound: {
} title: 'PÁGINA NÃO ENCONTRADA',
quote:
'Mas se você não mudar de direção e continuar procurando, pode acabar onde está indo.',
linkLabel: 'ir para a página inicial',
linkText: 'Me leve para casa'
}, },
langMenuLabel: 'Alterar Idioma', langMenuLabel: 'Alterar Idioma',
@ -167,8 +173,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] {
] ]
} }
export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
pt: { return {
placeholder: 'Pesquisar documentos', placeholder: 'Pesquisar documentos',
translations: { translations: {
button: { button: {
@ -177,35 +183,69 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: 'Limpar pesquisa', clearButtonTitle: 'Limpar pesquisa',
resetButtonAriaLabel: 'Limpar pesquisa', clearButtonAriaLabel: 'Limpar pesquisa',
cancelButtonText: 'Cancelar', closeButtonText: 'Fechar',
cancelButtonAriaLabel: 'Cancelar' closeButtonAriaLabel: 'Fechar',
placeholderText: 'Pesquisar documentos',
placeholderTextAskAi: 'Pergunte à IA: ',
placeholderTextAskAiStreaming: 'Respondendo...',
searchInputLabel: 'Pesquisar',
backToKeywordSearchButtonText: 'Voltar à pesquisa por palavras-chave',
backToKeywordSearchButtonAriaLabel:
'Voltar à pesquisa por palavras-chave'
}, },
startScreen: { startScreen: {
recentSearchesTitle: 'Histórico de Pesquisa', recentSearchesTitle: 'Histórico de pesquisa',
noRecentSearchesText: 'Nenhuma pesquisa recente', noRecentSearchesText: 'Nenhuma pesquisa recente',
saveRecentSearchButtonTitle: 'Salvar no histórico de pesquisas', saveRecentSearchButtonTitle: 'Salvar no histórico de pesquisas',
removeRecentSearchButtonTitle: 'Remover do histórico de pesquisas', removeRecentSearchButtonTitle: 'Remover do histórico de pesquisas',
favoriteSearchesTitle: 'Favoritos', favoriteSearchesTitle: 'Favoritos',
removeFavoriteSearchButtonTitle: 'Remover dos favoritos' removeFavoriteSearchButtonTitle: 'Remover dos favoritos',
recentConversationsTitle: 'Conversas recentes',
removeRecentConversationButtonTitle:
'Remover esta conversa do histórico'
}, },
errorScreen: { errorScreen: {
titleText: 'Não foi possível obter resultados', titleText: 'Não foi possível obter resultados',
helpText: 'Verifique a sua conexão de rede' helpText: 'Verifique sua conexão de rede'
},
noResultsScreen: {
noResultsText: 'Nenhum resultado encontrado',
suggestedQueryText: 'Você pode tentar uma nova consulta',
reportMissingResultsText: 'Acha que deveria haver resultados?',
reportMissingResultsLinkText: 'Clique para enviar feedback'
},
resultsScreen: {
askAiPlaceholder: 'Pergunte à IA: '
},
askAiScreen: {
disclaimerText:
'As respostas são geradas por IA e podem conter erros. Verifique as respostas.',
relatedSourcesText: 'Fontes relacionadas',
thinkingText: 'Pensando...',
copyButtonText: 'Copiar',
copyButtonCopiedText: 'Copiado!',
copyButtonTitle: 'Copiar',
likeButtonTitle: 'Curtir',
dislikeButtonTitle: 'Não curtir',
thanksForFeedbackText: 'Obrigado pelo feedback!',
preToolCallText: 'Pesquisando...',
duringToolCallText: 'Pesquisando ',
afterToolCallText: 'Pesquisa concluída',
aggregatedToolCallText: 'Pesquisa concluída'
}, },
footer: { footer: {
selectText: 'Selecionar', selectText: 'Selecionar',
submitQuestionText: 'Enviar pergunta',
selectKeyAriaLabel: 'Tecla Enter',
navigateText: 'Navegar', navigateText: 'Navegar',
navigateUpKeyAriaLabel: 'Seta para cima',
navigateDownKeyAriaLabel: 'Seta para baixo',
closeText: 'Fechar', closeText: 'Fechar',
searchByText: 'Pesquisa por' backToSearchText: 'Voltar à pesquisa',
}, closeKeyAriaLabel: 'Tecla Escape',
noResultsScreen: { poweredByText: 'Pesquisa por'
noResultsText: 'Não foi possível encontrar resultados',
suggestedQueryText: 'Você pode tentar uma nova consulta',
reportMissingResultsText:
'Deveriam haver resultados para essa consulta?',
reportMissingResultsLinkText: 'Clique para enviar feedback'
} }
} }
} }

@ -163,7 +163,7 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # ou pnpm / yarn cache: npm # ou pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ Se a sua fonte é um arquivo local referenciado via `@font-face`, ela será proc
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// ajuste o regex para corresponder à sua fonte // ajuste o regex para corresponder à sua fonte
const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -251,6 +251,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )

@ -39,22 +39,6 @@ $ bun add -D vitepress
::: :::
::: details Está recebendo avisos sobre dependências correspondentes ausentes?
Se usar PNPM, você perceberá um aviso de ausência de `@docsearch/js`. Isso não evita que o VitePress funcione. Se você deseja suprimir este aviso, adicione o seguinte no seu `package.json`:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip NOTA ::: tip NOTA
VitePress é um pacote apenas para ESM. Não use `require()` para importá-lo, e certifique de que o `package.json` mais próximo contém `"type": "module"`, ou mude a extensão do arquivo de seus arquivos releavantes como `.vitepress/config.js` para `.mjs`/`.mts`. Refira-se ao [Guia de resolução de problemas Vite](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) para mais detalhes. Além disso, dentro de contextos de JavaScript comum assíncronos, você pode usar `await import('vitepress')`. VitePress é um pacote apenas para ESM. Não use `require()` para importá-lo, e certifique de que o `package.json` mais próximo contém `"type": "module"`, ou mude a extensão do arquivo de seus arquivos releavantes como `.vitepress/config.js` para `.mjs`/`.mts`. Refira-se ao [Guia de resolução de problemas Vite](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) para mais detalhes. Além disso, dentro de contextos de JavaScript comum assíncronos, você pode usar `await import('vitepress')`.

@ -255,7 +255,7 @@ A classe `vp-raw` também pode ser usada diretamente em elementos. O isolamento
} }
``` ```
Ele utiliza [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) internamente. Você pode passar opções assim: Ele utiliza [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector) internamente. Você pode passar opções assim:
```js ```js
postcssIsolateStyles({ postcssIsolateStyles({

@ -12,7 +12,7 @@ Quer apenas experimentar? Pule para o [Início Rápido](./getting-started).
- **Documentação** - **Documentação**
VitePress vem com um tema padrão projetado para documentação técnica. Ele alimenta esta página que você está lendo agora, juntamente com a documentação [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) e [muitos outros](https://www.vuetelescope.com/explore?framework.slug=vitepress). VitePress vem com um tema padrão projetado para documentação técnica. Ele alimenta esta página que você está lendo agora, juntamente com a documentação [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) e [muitos outros](https://github.com/search?q=/"vitepress":+/+language:json&type=code).
A [documentação oficial Vue.js](https://vuejs.org/) também é baseada em VitePress, mas usa um tema personalizado compartilhado entre várias traduções. A [documentação oficial Vue.js](https://vuejs.org/) também é baseada em VitePress, mas usa um tema personalizado compartilhado entre várias traduções.

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: VitePress
titleTemplate: Gerador de Site Estático desenvolvido com Vite & Vue
hero: hero:
name: VitePress name: VitePress
text: Gerador de Site Estático Vite & Vue text: Gerador de Site Estático Vite & Vue

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | Caminho base público (padrão: `/`) (`string`) | | `--base <path>` | Caminho base público (padrão: `/`) (`string`) |
| `--target <target>` | Transpila o alvo (padrão: `"modules"`) (`string`) | | `--target <target>` | Transpila o alvo (padrão: `"modules"`) (`string`) |
| `--outDir <dir>` | Diretório de saída relativo ao **cwd** (padrão: `<root>/.vitepress/dist`) (`string`) | | `--outDir <dir>` | Diretório de saída relativo ao **cwd** (padrão: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | Habilita/desabilita minificação, ou especifica um minificador para usar (padrão: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | Limite em bytes para alinhar ativos em base64 (padrão: `4096`) (`number`) | | `--assetsInlineLimit <number>` | Limite em bytes para alinhar ativos em base64 (padrão: `4096`) (`number`) |
## `vitepress preview` ## `vitepress preview`

@ -370,3 +370,20 @@ new Crawler({
} }
}) })
``` ```
### Suporte ao Algolia Ask AI {#ask-ai}
Se quiser incluir o **Ask AI**, adicione `askAi` em `options`:
```ts
options: {
appId: '...',
apiKey: '...',
indexName: '...',
askAi: { assistantId: 'XXXYYY' }
}
```
::: warning Nota
Caso queira apenas a pesquisa por palavra-chave, omita `askAi`.
:::

@ -180,36 +180,3 @@ export default {
} }
} }
``` ```
## `useSidebar` <Badge type="info" text="composable" />
Retorna dados relacionados à barra lateral. O objeto retornado tem o seguinte tipo:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**Exemplo:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">Visível apenas quando a barra lateral existe</div>
</template>
```

@ -53,12 +53,12 @@ const members = [
Diga olá à nossa equipe incrível. Diga olá à nossa equipe incrível.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
``` ```
O código acima exibirá um membro da equipe em um elemento tipo cartão. Ele deve exibir algo semelhante ao abaixo. O código acima exibirá um membro da equipe em um elemento tipo cartão. Ele deve exibir algo semelhante ao abaixo.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
O componente `<VPTeamMembers>` vem em 2 tamanhos diferentes, pequeno `small` e médio `medium`. Enquanto é uma questão de preferência, geralmente o tamanho `small` deve encaixar melhor quando usado na página de documento. Além disso, você pode adicionar mais propriedades a cada membro, como adicionar o botão "descrição" ou "patrocinador". Saiba mais sobre em [`<VPTeamMembers>`](#vpteammembers). O componente `<VPTeamMembers>` vem em 2 tamanhos diferentes, pequeno `small` e médio `medium`. Enquanto é uma questão de preferência, geralmente o tamanho `small` deve encaixar melhor quando usado na página de documento. Além disso, você pode adicionar mais propriedades a cada membro, como adicionar o botão "descrição" ou "patrocinador". Saiba mais sobre em [`<VPTeamMembers>`](#vpteammembers).
@ -107,9 +107,7 @@ const members = [
alguns dos membros escolheram ser apresentados abaixo. alguns dos membros escolheram ser apresentados abaixo.
</template> </template>
</VPTeamPageTitle> </VPTeamPageTitle>
<VPTeamMembers <VPTeamMembers :members />
:members="members"
/>
</VPTeamPage> </VPTeamPage>
``` ```

@ -439,7 +439,7 @@ export default {
### ignoreDeadLinks ### ignoreDeadLinks
- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` - Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- Padrão: `false` - Padrão: `false`
Quando definido como `true`, VitePress não falhará na compilação devido a links quebrados. Quando definido como `true`, VitePress não falhará na compilação devido a links quebrados.

@ -1,16 +1,18 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const ru = defineConfig({ export default defineAdditionalConfig({
lang: 'ru-RU', lang: 'ru-RU',
description: 'Генератор статических сайтов на основе Vite и Vue.', description: 'Генератор статических сайтов на основе Vite и Vue.',
themeConfig: { themeConfig: {
nav: nav(), nav: nav(),
search: { options: searchOptions() },
sidebar: { sidebar: {
'/ru/guide/': { base: '/ru/guide/', items: sidebarGuide() }, '/ru/guide/': { base: '/ru/guide/', items: sidebarGuide() },
'/ru/reference/': { base: '/ru/reference/', items: sidebarReference() } '/ru/reference/': { base: '/ru/reference/', items: sidebarReference() }
@ -37,6 +39,14 @@ export const ru = defineConfig({
text: 'Обновлено' text: 'Обновлено'
}, },
notFound: {
title: 'СТРАНИЦА НЕ НАЙДЕНА',
quote:
'Но если ты не изменишь направление и продолжишь искать, ты можешь оказаться там, куда направляешься.',
linkLabel: 'перейти на главную',
linkText: 'Отведи меня домой'
},
darkModeSwitchLabel: 'Оформление', darkModeSwitchLabel: 'Оформление',
lightModeSwitchTitle: 'Переключить на светлую тему', lightModeSwitchTitle: 'Переключить на светлую тему',
darkModeSwitchTitle: 'Переключить на тёмную тему', darkModeSwitchTitle: 'Переключить на тёмную тему',
@ -163,8 +173,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] {
] ]
} }
export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
ru: { return {
placeholder: 'Поиск в документации', placeholder: 'Поиск в документации',
translations: { translations: {
button: { button: {
@ -173,10 +183,18 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: 'Сбросить поиск', clearButtonTitle: 'Очистить поиск',
resetButtonAriaLabel: 'Сбросить поиск', clearButtonAriaLabel: 'Очистить поиск',
cancelButtonText: 'Отменить поиск', closeButtonText: 'Закрыть',
cancelButtonAriaLabel: 'Отменить поиск' closeButtonAriaLabel: 'Закрыть',
placeholderText: 'Поиск в документации',
placeholderTextAskAi: 'Задайте вопрос ИИ: ',
placeholderTextAskAiStreaming: 'Формируется ответ...',
searchInputLabel: 'Поиск',
backToKeywordSearchButtonText:
'Вернуться к поиску по ключевым словам',
backToKeywordSearchButtonAriaLabel:
'Вернуться к поиску по ключевым словам'
}, },
startScreen: { startScreen: {
recentSearchesTitle: 'История поиска', recentSearchesTitle: 'История поиска',
@ -184,24 +202,50 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
saveRecentSearchButtonTitle: 'Сохранить в истории поиска', saveRecentSearchButtonTitle: 'Сохранить в истории поиска',
removeRecentSearchButtonTitle: 'Удалить из истории поиска', removeRecentSearchButtonTitle: 'Удалить из истории поиска',
favoriteSearchesTitle: 'Избранное', favoriteSearchesTitle: 'Избранное',
removeFavoriteSearchButtonTitle: 'Удалить из избранного' removeFavoriteSearchButtonTitle: 'Удалить из избранного',
recentConversationsTitle: 'Недавние диалоги',
removeRecentConversationButtonTitle: 'Удалить этот диалог из истории'
}, },
errorScreen: { errorScreen: {
titleText: 'Невозможно получить результаты', titleText: 'Невозможно получить результаты',
helpText: 'Вам может потребоваться проверить подключение к Интернету' helpText: 'Проверьте подключение к Интернету'
},
noResultsScreen: {
noResultsText: 'Ничего не найдено',
suggestedQueryText: 'Попробуйте изменить запрос',
reportMissingResultsText: 'Считаете, что результаты должны быть?',
reportMissingResultsLinkText: 'Сообщите об этом'
},
resultsScreen: {
askAiPlaceholder: 'Задайте вопрос ИИ: '
},
askAiScreen: {
disclaimerText:
'Ответы генерируются ИИ и могут содержать ошибки. Проверяйте информацию.',
relatedSourcesText: 'Связанные источники',
thinkingText: 'Думаю...',
copyButtonText: 'Копировать',
copyButtonCopiedText: 'Скопировано!',
copyButtonTitle: 'Копировать',
likeButtonTitle: 'Нравится',
dislikeButtonTitle: 'Не нравится',
thanksForFeedbackText: 'Спасибо за отзыв!',
preToolCallText: 'Поиск...',
duringToolCallText: 'Поиск ',
afterToolCallText: 'Поиск завершён',
aggregatedToolCallText: 'Поиск завершён'
}, },
footer: { footer: {
selectText: 'выбрать', selectText: 'выбрать',
submitQuestionText: 'Отправить вопрос',
selectKeyAriaLabel: 'Клавиша Enter',
navigateText: 'перейти', navigateText: 'перейти',
navigateUpKeyAriaLabel: 'Стрелка вверх',
navigateDownKeyAriaLabel: 'Стрелка вниз',
closeText: 'закрыть', closeText: 'закрыть',
searchByText: 'поставщик поиска' backToSearchText: 'Вернуться к поиску',
}, closeKeyAriaLabel: 'Клавиша Esc',
noResultsScreen: { poweredByText: 'поиск от'
noResultsText: 'Нет результатов для',
suggestedQueryText: 'Вы можете попытаться узнать',
reportMissingResultsText:
'Считаете, что поиск даёт ложные результаты?',
reportMissingResultsLinkText: 'Нажмите на кнопку «Обратная связь»'
} }
} }
} }

@ -111,7 +111,7 @@ Cache-Control: max-age=31536000,immutable
- **Build Command:** `npm run docs:build` - **Build Command:** `npm run docs:build`
- **Output Directory:** `docs/.vitepress/dist` - **Output Directory:** `docs/.vitepress/dist`
- **Node Version:** `18` (или выше) - **Node Version:** `20` (или выше)
::: warning ПРЕДУПРЕЖДЕНИЕ ::: warning ПРЕДУПРЕЖДЕНИЕ
Не включайте такие опции, как _Auto Minify_ для HTML-кода. Он удалит из вывода комментарии, которые имеют значение для Vue. При их удалении могут возникать ошибки несоответствия гидратации. Не включайте такие опции, как _Auto Minify_ для HTML-кода. Он удалит из вывода комментарии, которые имеют значение для Vue. При их удалении могут возникать ошибки несоответствия гидратации.
@ -163,7 +163,7 @@ Cache-Control: max-age=31536000,immutable
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # или pnpm / yarn cache: npm # или pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ export default DefaultTheme
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// настраиваем regex соответствующим образом, чтобы он соответствовал вашему шрифту // настраиваем regex соответствующим образом, чтобы он соответствовал вашему шрифту
const myFontFile = assets.find((file) => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -253,6 +253,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )

@ -39,22 +39,6 @@ $ bun add -D vitepress
::: :::
::: details Получаете предупреждения об отсутствующих зависимостях?
Если вы используете PNPM, вы заметите предупреждение об отсутствующем пакете `@docsearch/js`. Это не мешает работе VitePress. Если вы хотите подавить это предупреждение, добавьте следующее в ваш `package.json`:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip ПРИМЕЧАНИЕ ::: tip ПРИМЕЧАНИЕ
VitePress — это пакет, предназначенный только для ESM. Не используйте `require()` для импорта, и убедитесь, что ближайший `package.json` содержит `"type": "module"`, или измените расширение соответствующих файлов, например, `.vitepress/config.js` на `.mjs`/`.mts`. Более подробную информацию см. в [Руководстве по устранению неполадок Vite](https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only). Кроме того, внутри асинхронных контекстов CJS можно использовать `await import('vitepress')` вместо этого. VitePress — это пакет, предназначенный только для ESM. Не используйте `require()` для импорта, и убедитесь, что ближайший `package.json` содержит `"type": "module"`, или измените расширение соответствующих файлов, например, `.vitepress/config.js` на `.mjs`/`.mts`. Более подробную информацию см. в [Руководстве по устранению неполадок Vite](https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only). Кроме того, внутри асинхронных контекстов CJS можно использовать `await import('vitepress')` вместо этого.

@ -281,7 +281,7 @@ console.log('Привет, VitePress!')
} }
``` ```
Он использует [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) под капотом. Вы можете передать ему параметры следующим образом: Он использует [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector) под капотом. Вы можете передать ему параметры следующим образом:
```js ```js
postcssIsolateStyles({ postcssIsolateStyles({
@ -783,7 +783,7 @@ export default config
Вы можете включить файл Markdown в другой файл Markdown, даже вложенный. Вы можете включить файл Markdown в другой файл Markdown, даже вложенный.
::: tip СОВЕТ ::: tip СОВЕТ
Вы также можете добавить в префикс пути к Markdown символ `@`, он будет выступать в качестве корня источника. По умолчанию это корень проекта VitePress, если не настроена опция `srcDir`. Вы также можете добавить префикс `@` к пути Markdown, и он будет считаться корневой папкой исходников. По умолчанию корневая папка исходников совпадает с корнем проекта VitePress, если не настроен параметр `srcDir`.
::: :::
Например, вы можете включить относительный файл Markdown следующим образом: Например, вы можете включить относительный файл Markdown следующим образом:

@ -12,7 +12,7 @@ VitePress — это [Генератор статических сайтов](ht
- **Документация** - **Документация**
VitePress поставляется с темой по умолчанию, предназначенной для технической документации. Она содержит эту страницу, которую вы сейчас читаете, а также документацию по [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) и [многое другое](https://www.vuetelescope.com/explore?framework.slug=vitepress). VitePress поставляется с темой по умолчанию, предназначенной для технической документации. Она содержит эту страницу, которую вы сейчас читаете, а также документацию по [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) и [многое другое](https://github.com/search?q=/"vitepress":+/+language:json&type=code).
[Официальная документация Vue.js](https://vuejs.org/) также основана на VitePress, но использует пользовательскую тему, разделяемую между несколькими переводами. [Официальная документация Vue.js](https://vuejs.org/) также основана на VitePress, но использует пользовательскую тему, разделяемую между несколькими переводами.

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: VitePress
titleTemplate: Генератор статических сайтов на основе Vite и Vue
hero: hero:
name: VitePress name: VitePress
text: Генератор статических сайтов на основе Vite и Vue text: Генератор статических сайтов на основе Vite и Vue

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | Публичный базовый путь (по умолчанию: `/`) (`string`) | | `--base <path>` | Публичный базовый путь (по умолчанию: `/`) (`string`) |
| `--target <target>` | Транспилировать цель (по умолчанию: `"modules"`) (`string`) | | `--target <target>` | Транспилировать цель (по умолчанию: `"modules"`) (`string`) |
| `--outDir <dir>` | Выходной каталог относительно **cwd** (по умолчанию: `<root>/.vitepress/dist`) (`string`) | | `--outDir <dir>` | Выходной каталог относительно **cwd** (по умолчанию: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | Включить/выключить минификацию или задать используемый минификатор (по умолчанию: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | Статический встроенный порог ресурса base64 в байтах (по умолчанию: `4096`) (`number`) | | `--assetsInlineLimit <number>` | Статический встроенный порог ресурса base64 в байтах (по умолчанию: `4096`) (`number`) |
## `vitepress preview` {#vitepress-preview} ## `vitepress preview` {#vitepress-preview}

@ -19,13 +19,13 @@ export default {
**Параметры, описанные на этой странице, применимы только к теме по умолчанию.** Разные темы предполагают разные конфигурации темы. При использовании пользовательской темы объект конфигурации темы будет передан теме, чтобы она могла определить условное поведение на его основе. **Параметры, описанные на этой странице, применимы только к теме по умолчанию.** Разные темы предполагают разные конфигурации темы. При использовании пользовательской темы объект конфигурации темы будет передан теме, чтобы она могла определить условное поведение на его основе.
## i18nRouting {#i18nrouting} ## i18nRouting
- Тип: `boolean` - Тип: `boolean`
При смене локали на `ru` URL изменится с `/foo` (или `/en/foo/`) на `/ru/foo`. Вы можете отключить это поведение, установив для параметра `themeConfig.i18nRouting` значение `false`. При смене локали на `ru` URL изменится с `/foo` (или `/en/foo/`) на `/ru/foo`. Вы можете отключить это поведение, установив для параметра `themeConfig.i18nRouting` значение `false`.
## logo {#logo} ## logo
- Тип: `ThemeableImage` - Тип: `ThemeableImage`
@ -46,7 +46,7 @@ type ThemeableImage =
| { light: string; dark: string; alt?: string } | { light: string; dark: string; alt?: string }
``` ```
## siteTitle {#sitetitle} ## siteTitle
- Тип: `string | false` - Тип: `string | false`
@ -60,7 +60,7 @@ export default {
} }
``` ```
## nav {#nav} ## nav
- Тип: `NavItem` - Тип: `NavItem`
@ -108,7 +108,7 @@ interface NavItemWithChildren {
} }
``` ```
## sidebar {#sidebar} ## sidebar
- Тип: `Sidebar` - Тип: `Sidebar`
@ -135,7 +135,7 @@ export default {
export type Sidebar = SidebarItem[] | SidebarMulti export type Sidebar = SidebarItem[] | SidebarMulti
export interface SidebarMulti { export interface SidebarMulti {
[path: string]: SidebarItem[] [path: string]: SidebarItem[] | { items: SidebarItem[]; base: string }
} }
export type SidebarItem = { export type SidebarItem = {
@ -162,10 +162,23 @@ export type SidebarItem = {
* Если `false`, группа сворачивается, но по умолчанию разворачивается * Если `false`, группа сворачивается, но по умолчанию разворачивается
*/ */
collapsed?: boolean collapsed?: boolean
/**
* Базовый путь для дочерних элементов
*/
base?: string
/**
* Настройте текст, который отображается в футере предыдущей/следующей страницы
*/
docFooterText?: string
rel?: string
target?: string
} }
``` ```
## aside {#aside} ## aside
- Тип: `boolean | 'left'` - Тип: `boolean | 'left'`
- По умолчанию: `true` - По умолчанию: `true`
@ -177,7 +190,7 @@ export type SidebarItem = {
Если вы хотите отключить его для всех режимов просмотра, используйте `aside: false`. Если вы хотите отключить его для всех режимов просмотра, используйте `aside: false`.
## outline {#outline} ## outline
- Тип: `Outline | Outline['level'] | false` - Тип: `Outline | Outline['level'] | false`
- Уровень можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#outline) - Уровень можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#outline)
@ -205,7 +218,7 @@ interface Outline {
} }
``` ```
## socialLinks {#sociallinks} ## socialLinks
- Тип: `SocialLink[]` - Тип: `SocialLink[]`
@ -215,6 +228,7 @@ interface Outline {
export default { export default {
themeConfig: { themeConfig: {
socialLinks: [ socialLinks: [
// Можно добавить любую иконку из simple-icons (https://simpleicons.org/):
{ icon: 'github', link: 'https://github.com/vuejs/vitepress' }, { icon: 'github', link: 'https://github.com/vuejs/vitepress' },
{ icon: 'twitter', link: '...' }, { icon: 'twitter', link: '...' },
// Можно добавить пользовательские иконки, передав SVG в виде строки: // Можно добавить пользовательские иконки, передав SVG в виде строки:
@ -239,7 +253,7 @@ interface SocialLink {
} }
``` ```
## footer {#footer} ## footer
- Тип: `Footer` - Тип: `Footer`
- Можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#footer) - Можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#footer)
@ -264,7 +278,7 @@ export interface Footer {
} }
``` ```
## editLink {#editlink} ## editLink
- Тип: `EditLink` - Тип: `EditLink`
- Можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#editlink) - Можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#editlink)
@ -289,7 +303,7 @@ export interface EditLink {
} }
``` ```
## lastUpdated {#lastupdated} ## lastUpdated
- Тип: `LastUpdatedOptions` - Тип: `LastUpdatedOptions`
@ -324,7 +338,7 @@ export interface LastUpdatedOptions {
} }
``` ```
## algolia {#algolia} ## algolia
- Тип: `AlgoliaSearch` - Тип: `AlgoliaSearch`
@ -364,7 +378,7 @@ export interface CarbonAdsOptions {
Подробнее в главе [Тема по умолчанию: Carbon Ads](./default-theme-carbon-ads) Подробнее в главе [Тема по умолчанию: Carbon Ads](./default-theme-carbon-ads)
## docFooter {#docfooter} ## docFooter
- Тип: `DocFooter` - Тип: `DocFooter`
@ -388,47 +402,47 @@ export interface DocFooter {
} }
``` ```
## darkModeSwitchLabel {#darkmodeswitchlabel} ## darkModeSwitchLabel
- Тип: `string` - Тип: `string`
- По умолчанию: `Appearance` - По умолчанию: `Appearance`
Можно использовать для настройки надписи переключателя тёмного режима. Этот ярлык отображается только в мобильном представлении. Можно использовать для настройки надписи переключателя тёмного режима. Этот ярлык отображается только в мобильном представлении.
## lightModeSwitchTitle {#lightmodeswitchtitle} ## lightModeSwitchTitle
- Тип: `string` - Тип: `string`
- По умолчанию: `Switch to light theme` - По умолчанию: `Switch to light theme`
Может использоваться для настройки заголовка переключателя светлого режима, который появляется при наведении курсора. Может использоваться для настройки заголовка переключателя светлого режима, который появляется при наведении курсора.
## darkModeSwitchTitle {#darkmodeswitchtitle} ## darkModeSwitchTitle
- Тип: `string` - Тип: `string`
- По умолчанию: `Switch to dark theme` - По умолчанию: `Switch to dark theme`
Можно использовать для настройки заголовка переключателя тёмного режима, который появляется при наведении курсора. Можно использовать для настройки заголовка переключателя тёмного режима, который появляется при наведении курсора.
## sidebarMenuLabel {#sidebarmenulabel} ## sidebarMenuLabel
- Тип: `string` - Тип: `string`
- По умолчанию: `Menu` - По умолчанию: `Menu`
Может использоваться для настройки метки бокового меню. Эта метка отображается только в мобильном представлении. Может использоваться для настройки метки бокового меню. Эта метка отображается только в мобильном представлении.
## returnToTopLabel {#returntotoplabel} ## returnToTopLabel
- Тип: `string` - Тип: `string`
- По умолчанию: `Return to top` - По умолчанию: `Return to top`
Может использоваться для настройки метки кнопки возврата наверх. Эта метка отображается только в мобильном представлении. Может использоваться для настройки метки кнопки возврата наверх. Эта метка отображается только в мобильном представлении.
## langMenuLabel {#langmenulabel} ## langMenuLabel
- Тип: `string` - Тип: `string`
- По умолчанию: `Change language` - По умолчанию: `Change language`
Можно использовать для настройки aria-метки кнопки переключения языка в панели навигации. Это используется только в том случае, если вы используете [i18n](../guide/i18n). Можно использовать для настройки aria-метки кнопки переключения языка в панели навигации. Применяется только в том случае, если вы используете [i18n](../guide/i18n).
## skipToContentLabel ## skipToContentLabel
@ -437,9 +451,44 @@ export interface DocFooter {
Можно использовать для настройки метки ссылки перехода к содержимому. Эта ссылка отображается, когда пользователь перемещается по сайту с помощью клавиатуры. Можно использовать для настройки метки ссылки перехода к содержимому. Эта ссылка отображается, когда пользователь перемещается по сайту с помощью клавиатуры.
## externalLinkIcon {#externallinkicon} ## externalLinkIcon
- Тип: `boolean` - Тип: `boolean`
- По умолчанию: `false` - По умолчанию: `false`
Отображать ли значок внешней ссылки рядом с внешними ссылками в Markdown. Отображать ли значок внешней ссылки рядом с внешними ссылками в Markdown.
## `useLayout` <Badge type="info" text="composable" />
Возвращает данные, относящиеся к макету. Возвращаемый объект имеет следующий тип:
```ts
interface {
isHome: ComputedRef<boolean>
sidebar: Readonly<ShallowRef<DefaultTheme.SidebarItem[]>>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
headers: Readonly<ShallowRef<DefaultTheme.OutlineItem[]>>
hasLocalNav: ComputedRef<boolean>
}
```
**Пример:**
```vue
<script setup>
import { useLayout } from 'vitepress/theme'
const { hasSidebar } = useLayout()
</script>
<template>
<div v-if="hasSidebar">Отображается только если есть боковая панель</div>
</template>
```

@ -2,8 +2,27 @@
Время последнего обновления содержимого будет отображаться в правом нижнем углу страницы. Чтобы включить его, добавьте опцию `lastUpdated` в свой конфиг. Время последнего обновления содержимого будет отображаться в правом нижнем углу страницы. Чтобы включить его, добавьте опцию `lastUpdated` в свой конфиг.
::: tip Совет ::: info ПРИМЕЧАНИЕ
Чтобы увидеть обновленное время, необходимо зафиксировать файл Markdown. VitePress отображает время «последнего обновления» на основе временной метки последнего Git-коммита для каждого файла. Для работы этой функции Markdown-файл должен быть закоммичен в Git.
Внутри VitePress выполняет команду `git log -1 --pretty="%ai"` для каждого файла, чтобы получить его временную метку. Если все страницы показывают одинаковое время обновления, вероятно, это связано с поверхностным клонированием (часто встречается в CI-средах), которое ограничивает историю Git.
Чтобы исправить это в **GitHub Actions**, добавьте следующее в ваш workflow-файл:
```yaml{4}
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
```
Другие CI/CD-платформы имеют аналогичные настройки.
Если такие опции недоступны, вы можете добавить принудительный fetch перед командой `docs:build` в вашем `package.json`:
```json
"docs:build": "git fetch --unshallow && vitepress build docs"
```
::: :::
## Настройка в файле конфигурации {#site-level-config} ## Настройка в файле конфигурации {#site-level-config}

@ -233,10 +233,16 @@ export default defineConfig({
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: 'Сбросить поиск', clearButtonTitle: 'Очистить поиск',
resetButtonAriaLabel: 'Сбросить поиск', clearButtonAriaLabel: 'Очистить поиск',
cancelButtonText: 'Отменить поиск', closeButtonText: 'Закрыть',
cancelButtonAriaLabel: 'Отменить поиск' closeButtonAriaLabel: 'Закрыть',
placeholderText: 'Поиск в документации',
placeholderTextAskAi: 'Задайте вопрос ИИ:',
placeholderTextAskAiStreaming: 'Формируется ответ...',
searchInputLabel: 'Поиск',
backToKeywordSearchButtonText: 'Вернуться к поиску по ключевым словам',
backToKeywordSearchButtonAriaLabel: 'Вернуться к поиску по ключевым словам'
}, },
startScreen: { startScreen: {
recentSearchesTitle: 'История поиска', recentSearchesTitle: 'История поиска',
@ -244,26 +250,48 @@ export default defineConfig({
saveRecentSearchButtonTitle: 'Сохранить в истории поиска', saveRecentSearchButtonTitle: 'Сохранить в истории поиска',
removeRecentSearchButtonTitle: 'Удалить из истории поиска', removeRecentSearchButtonTitle: 'Удалить из истории поиска',
favoriteSearchesTitle: 'Избранное', favoriteSearchesTitle: 'Избранное',
removeFavoriteSearchButtonTitle: 'Удалить из избранного' removeFavoriteSearchButtonTitle: 'Удалить из избранного',
recentConversationsTitle: 'Последние диалоги',
removeRecentConversationButtonTitle: 'Удалить диалог из истории'
}, },
errorScreen: { errorScreen: {
titleText: 'Невозможно получить результаты', titleText: 'Невозможно получить результаты',
helpText: helpText: 'Проверьте подключение к Интернету'
'Вам может потребоваться проверить подключение к Интернету' },
noResultsScreen: {
noResultsText: 'Ничего не найдено',
suggestedQueryText: 'Попробуйте изменить запрос',
reportMissingResultsText: 'Считаете, что результаты должны быть?',
reportMissingResultsLinkText: 'Сообщите об этом'
},
resultsScreen: {
askAiPlaceholder: 'Задайте вопрос ИИ: '
},
askAiScreen: {
disclaimerText: 'Ответ сгенерирован ИИ и может быть неточным. Пожалуйста, проверьте информацию самостоятельно.',
relatedSourcesText: 'Связанные источники',
thinkingText: 'Думаю...',
copyButtonText: 'Копировать',
copyButtonCopiedText: 'Скопировано!',
copyButtonTitle: 'Копировать',
likeButtonTitle: 'Нравится',
dislikeButtonTitle: 'Не нравится',
thanksForFeedbackText: 'Спасибо за ваш отзыв!',
preToolCallText: 'Идёт поиск...',
duringToolCallText: 'Поиск ',
afterToolCallText: 'Поиск выполнен'
}, },
footer: { footer: {
selectText: 'выбрать', selectText: 'выбрать',
submitQuestionText: 'Отправить вопрос',
selectKeyAriaLabel: 'Клавиша Enter',
navigateText: 'перейти', navigateText: 'перейти',
navigateUpKeyAriaLabel: 'Стрелка вверх',
navigateDownKeyAriaLabel: 'Стрелка вниз',
closeText: 'закрыть', closeText: 'закрыть',
searchByText: 'поставщик поиска' backToSearchText: 'Вернуться к поиску',
}, closeKeyAriaLabel: 'Клавиша Esc',
noResultsScreen: { poweredByText: 'поиск от'
noResultsText: 'Нет результатов для',
suggestedQueryText: 'Вы можете попытаться узнать',
reportMissingResultsText:
'Считаете, что поиск даёт ложные результаты?',
reportMissingResultsLinkText:
'Нажмите на кнопку «Обратная связь»'
} }
} }
} }
@ -277,6 +305,43 @@ export default defineConfig({
[Эти параметры](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) можно переопределить. Чтобы узнать о них больше, обратитесь к официальной документации Algolia. [Эти параметры](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) можно переопределить. Чтобы узнать о них больше, обратитесь к официальной документации Algolia.
### Поддержка Ask AI в Algolia {#ask-ai}
Если вы хотите добавить функцию **Ask AI**, передайте параметр `askAi` (или любые из его отдельных полей) внутри объекта `options`:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: '...',
apiKey: '...',
indexName: '...',
// askAi: "ID-ВАШЕГО-АССИСТЕНТА"
// ИЛИ
askAi: {
// минимум вы должны указать assistantId, полученный от Algolia
assistantId: 'XXXYYY',
// опциональные переопределения если не указаны, используются значения appId/apiKey/indexName верхнего уровня
// apiKey: '...',
// appId: '...',
// indexName: '...'
}
}
}
}
})
```
::: warning Примечание
Если вы хотите использовать обычный поиск по ключевым словам без Ask AI, просто не указывайте свойство `askAi`
:::
Переводы для интерфейса Ask AI находятся в `options.translations.modal.askAiScreen` и `options.translations.resultsScreen` — полный список ключей смотрите в [типах](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts).
### Конфигурация поискового робота {#crawler-config} ### Конфигурация поискового робота {#crawler-config}
Вот пример конфигурации, основанной на той, что используется на этом сайте: Вот пример конфигурации, основанной на той, что используется на этом сайте:

@ -178,36 +178,3 @@ export default {
} }
} }
``` ```
## `useSidebar` <Badge type="info" text="композабл" /> {#usesidebar}
Возвращает данные, связанные с сайдбаром. Возвращаемый объект имеет следующий тип:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**Пример:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">Показывать только при наличии сайдбара</div>
</template>
```

@ -51,12 +51,12 @@ const members = [
# Поприветствуйте нашу замечательную команду # Поприветствуйте нашу замечательную команду
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
``` ```
Вышеуказанное отобразит члена команды в виде карточки. Должно отобразиться что-то похожее на то, что показано ниже. Вышеуказанное отобразит члена команды в виде карточки. Должно отобразиться что-то похожее на то, что показано ниже.
<VPTeamMembers size="small" :members="members" /> <VPTeamMembers size="small" :members />
Компонент `<VPTeamMembers>` поставляется в двух различных размерах, `small` и `medium`. Хотя это зависит от ваших предпочтений, обычно размер `small` лучше подходит для использования на странице с макетом `doc`. Кроме того, вы можете добавить дополнительные свойства для карточки члена команды, например, добавить «описание» или кнопку «спонсировать». Подробнее об этом в секции [`<VPTeamMembers>`](#vpteammembers). Компонент `<VPTeamMembers>` поставляется в двух различных размерах, `small` и `medium`. Хотя это зависит от ваших предпочтений, обычно размер `small` лучше подходит для использования на странице с макетом `doc`. Кроме того, вы можете добавить дополнительные свойства для карточки члена команды, например, добавить «описание» или кнопку «спонсировать». Подробнее об этом в секции [`<VPTeamMembers>`](#vpteammembers).
@ -104,7 +104,7 @@ layout: page
которой представлены ниже. которой представлены ниже.
</template> </template>
</VPTeamPageTitle> </VPTeamPageTitle>
<VPTeamMembers :members="members" /> <VPTeamMembers :members />
</VPTeamPage> </VPTeamPage>
``` ```

@ -21,7 +21,7 @@ editLink: true
{{ $frontmatter.title }} {{ $frontmatter.title }}
``` ```
## title {#title} ## title
- Тип: `string` - Тип: `string`
@ -33,7 +33,7 @@ title: VitePress
--- ---
``` ```
## titleTemplate {#titletemplate} ## titleTemplate
- Тип: `string | boolean` - Тип: `string | boolean`
@ -46,7 +46,7 @@ titleTemplate: Генератор статических сайтов на ос
--- ---
``` ```
## description {#description} ## description
- Тип: `string` - Тип: `string`
@ -58,7 +58,7 @@ description: VitePress
--- ---
``` ```
## head {#head} ## head
- Тип: `HeadConfig[]` - Тип: `HeadConfig[]`
@ -86,7 +86,7 @@ type HeadConfig =
Следующие параметры метаданных применимы только при использовании темы по умолчанию. Следующие параметры метаданных применимы только при использовании темы по умолчанию.
### layout {#layout} ### layout
- Тип: `doc | home | page` - Тип: `doc | home | page`
- По умолчанию: `doc` - По умолчанию: `doc`
@ -103,15 +103,15 @@ layout: doc
--- ---
``` ```
### hero <Badge type="info" text="только для страниц с макетом home" /> {#hero} ### hero <Badge type="info" text="только для страниц с макетом home" />
Определяет содержимое секции `hero`, когда `layout` имеет значение `home`. Подробнее в главе [Тема по умолчанию: Главная страница](./default-theme-home-page). Определяет содержимое секции `hero`, когда `layout` имеет значение `home`. Подробнее в главе [Тема по умолчанию: Главная страница](./default-theme-home-page).
### features <Badge type="info" text="только для страниц с макетом home" /> {#features} ### features <Badge type="info" text="только для страниц с макетом home" />
Определяет элементы для отображения в секции `features`, когда `layout` имеет значение `home`. Подробнее в главе [Тема по умолчанию: Главная страница](./default-theme-home-page). Определяет элементы для отображения в секции `features`, когда `layout` имеет значение `home`. Подробнее в главе [Тема по умолчанию: Главная страница](./default-theme-home-page).
### navbar {#navbar} ### navbar
- Тип: `boolean` - Тип: `boolean`
- По умолчанию: `true` - По умолчанию: `true`
@ -124,7 +124,7 @@ navbar: false
--- ---
``` ```
### sidebar {#sidebar} ### sidebar
- Тип: `boolean` - Тип: `boolean`
- По умолчанию: `true` - По умолчанию: `true`
@ -137,7 +137,7 @@ sidebar: false
--- ---
``` ```
### aside {#aside} ### aside
- Тип: `boolean | 'left'` - Тип: `boolean | 'left'`
- По умолчанию: `true` - По умолчанию: `true`
@ -154,7 +154,7 @@ aside: false
--- ---
``` ```
### outline {#outline} ### outline
- Тип: `number | [number, number] | 'deep' | false` - Тип: `number | [number, number] | 'deep' | false`
- По умолчанию: `2` - По умолчанию: `2`
@ -167,7 +167,7 @@ outline: [2, 4]
--- ---
``` ```
### lastUpdated {#lastupdated} ### lastUpdated
- Тип: `boolean | Date` - Тип: `boolean | Date`
- По умолчанию: `true` - По умолчанию: `true`
@ -180,7 +180,7 @@ lastUpdated: false
--- ---
``` ```
### editLink {#editlink} ### editLink
- Тип: `boolean` - Тип: `boolean`
- По умолчанию: `true` - По умолчанию: `true`
@ -193,7 +193,7 @@ editLink: false
--- ---
``` ```
### footer {#footer} ### footer
- Тип: `boolean` - Тип: `boolean`
- По умолчанию: `true` - По умолчанию: `true`
@ -206,7 +206,7 @@ footer: false
--- ---
``` ```
### pageClass {#pageclass} ### pageClass
- Тип: `string` - Тип: `string`
@ -225,3 +225,16 @@ pageClass: custom-page-class
/* стили для конкретной страницы */ /* стили для конкретной страницы */
} }
``` ```
### isHome
- Тип: `boolean`
Стандартная тема полагается на проверки типа `frontmatter.layout === 'home'`, чтобы определить, является ли текущая страница домашней (главной).\
Это полезно, когда вы хотите принудительно показывать элементы домашней страницы в пользовательском макете.
```yaml
---
isHome: true
---
```

@ -10,7 +10,7 @@ outline: deep
### Разрешение конфигурации {#config-resolution} ### Разрешение конфигурации {#config-resolution}
Файл конфигурации всегда разрешается из `<root>/.vitepress/config.[ext]`, где `<root>` — это корень вашего [проекта](../guide/routing#root-and-source-directory) VitePress, а `[ext]` — одно из поддерживаемых расширений файла. TypeScript поддерживается из коробки. Поддерживаемые расширения включают `.js`, `.ts`, `.mjs` и `.mts`. Конфигурация всегда считывается из файла `<root>/.vitepress/config.[ext]`, где `<root>` — это корень вашего [проекта](../guide/routing#root-and-source-directory) VitePress, а `[ext]` — одно из поддерживаемых расширений файла. TypeScript поддерживается из коробки. Поддерживаемые расширения включают `.js`, `.ts`, `.mjs` и `.mts`.
В файлах конфигурации рекомендуется использовать синтаксис ES-модулей. Файл конфигурации должен по умолчанию экспортировать объект: В файлах конфигурации рекомендуется использовать синтаксис ES-модулей. Файл конфигурации должен по умолчанию экспортировать объект:
@ -439,7 +439,7 @@ export default {
### ignoreDeadLinks {#ignoredeadlinks} ### ignoreDeadLinks {#ignoredeadlinks}
- Тип: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` - Тип: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- По умолчанию: `false` - По умолчанию: `false`
Если установлено значение `true`, VitePress не будет завершать сборку из-за неработающих ссылок. Если установлено значение `true`, VitePress не будет завершать сборку из-за неработающих ссылок.

@ -1,16 +1,18 @@
import { createRequire } from 'module' import { createRequire } from 'module'
import { defineConfig, type DefaultTheme } from 'vitepress' import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json') const pkg = require('vitepress/package.json')
export const zh = defineConfig({ export default defineAdditionalConfig({
lang: 'zh-Hans', lang: 'zh-Hans',
description: '由 Vite 和 Vue 驱动的静态站点生成器', description: '由 Vite 和 Vue 驱动的静态站点生成器',
themeConfig: { themeConfig: {
nav: nav(), nav: nav(),
search: { options: searchOptions() },
sidebar: { sidebar: {
'/zh/guide/': { base: '/zh/guide/', items: sidebarGuide() }, '/zh/guide/': { base: '/zh/guide/', items: sidebarGuide() },
'/zh/reference/': { base: '/zh/reference/', items: sidebarReference() } '/zh/reference/': { base: '/zh/reference/', items: sidebarReference() }
@ -36,11 +38,15 @@ export const zh = defineConfig({
}, },
lastUpdated: { lastUpdated: {
text: '最后更新于', text: '最后更新于'
formatOptions: { },
dateStyle: 'short',
timeStyle: 'medium' notFound: {
} title: '页面未找到',
quote:
'但如果你不改变方向,并且继续寻找,你可能最终会到达你所前往的地方。',
linkLabel: '前往首页',
linkText: '带我回首页'
}, },
langMenuLabel: '多语言', langMenuLabel: '多语言',
@ -160,8 +166,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] {
] ]
} }
export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
zh: { return {
placeholder: '搜索文档', placeholder: '搜索文档',
translations: { translations: {
button: { button: {
@ -170,10 +176,16 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
}, },
modal: { modal: {
searchBox: { searchBox: {
resetButtonTitle: '清除查询条件', clearButtonTitle: '清除查询条件',
resetButtonAriaLabel: '清除查询条件', clearButtonAriaLabel: '清除查询条件',
cancelButtonText: '取消', closeButtonText: '关闭',
cancelButtonAriaLabel: '取消' closeButtonAriaLabel: '关闭',
placeholderText: '搜索文档',
placeholderTextAskAi: '向 AI 提问:',
placeholderTextAskAiStreaming: '回答中...',
searchInputLabel: '搜索',
backToKeywordSearchButtonText: '返回关键字搜索',
backToKeywordSearchButtonAriaLabel: '返回关键字搜索'
}, },
startScreen: { startScreen: {
recentSearchesTitle: '搜索历史', recentSearchesTitle: '搜索历史',
@ -181,23 +193,49 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = {
saveRecentSearchButtonTitle: '保存至搜索历史', saveRecentSearchButtonTitle: '保存至搜索历史',
removeRecentSearchButtonTitle: '从搜索历史中移除', removeRecentSearchButtonTitle: '从搜索历史中移除',
favoriteSearchesTitle: '收藏', favoriteSearchesTitle: '收藏',
removeFavoriteSearchButtonTitle: '从收藏中移除' removeFavoriteSearchButtonTitle: '从收藏中移除',
recentConversationsTitle: '最近的对话',
removeRecentConversationButtonTitle: '从历史记录中删除对话'
}, },
errorScreen: { errorScreen: {
titleText: '无法获取结果', titleText: '无法获取结果',
helpText: '你可能需要检查你的网络连接' helpText: '你可能需要检查你的网络连接'
}, },
footer: {
selectText: '选择',
navigateText: '切换',
closeText: '关闭',
searchByText: '搜索提供者'
},
noResultsScreen: { noResultsScreen: {
noResultsText: '无法找到相关结果', noResultsText: '无法找到相关结果',
suggestedQueryText: '你可以尝试查询', suggestedQueryText: '你可以尝试查询',
reportMissingResultsText: '你认为该查询应该有结果?', reportMissingResultsText: '你认为该查询应该有结果?',
reportMissingResultsLinkText: '点击反馈' reportMissingResultsLinkText: '点击反馈'
},
resultsScreen: {
askAiPlaceholder: '向 AI 提问: '
},
askAiScreen: {
disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。',
relatedSourcesText: '相关来源',
thinkingText: '思考中...',
copyButtonText: '复制',
copyButtonCopiedText: '已复制!',
copyButtonTitle: '复制',
likeButtonTitle: '赞',
dislikeButtonTitle: '踩',
thanksForFeedbackText: '感谢你的反馈!',
preToolCallText: '搜索中...',
duringToolCallText: '搜索 ',
afterToolCallText: '已搜索',
aggregatedToolCallText: '已搜索'
},
footer: {
selectText: '选择',
submitQuestionText: '提交问题',
selectKeyAriaLabel: 'Enter 键',
navigateText: '切换',
navigateUpKeyAriaLabel: '向上箭头',
navigateDownKeyAriaLabel: '向下箭头',
closeText: '关闭',
backToSearchText: '返回搜索',
closeKeyAriaLabel: 'Esc 键',
poweredByText: '搜索提供者'
} }
} }
} }

@ -111,7 +111,7 @@ Cache-Control: max-age=31536000,immutable
- **构建命令:** `npm run docs:build` - **构建命令:** `npm run docs:build`
- **输出目录:** `docs/.vitepress/dist` - **输出目录:** `docs/.vitepress/dist`
- **node 版本:** `18` (或更高版本) - **node 版本:** `20` (或更高版本)
::: warning ::: warning
不要为 HTML 代码启用 _Auto Minify_ 等选项。它将从输出中删除对 Vue 有意义的注释。如果被删除,你可能会看到激活不匹配错误。 不要为 HTML 代码启用 _Auto Minify_ 等选项。它将从输出中删除对 Vue 有意义的注释。如果被删除,你可能会看到激活不匹配错误。
@ -163,7 +163,7 @@ Cache-Control: max-age=31536000,immutable
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: npm # 或 pnpm / yarn cache: npm # 或 pnpm / yarn
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v4 uses: actions/configure-pages@v4

@ -70,7 +70,7 @@ export default DefaultTheme
export default { export default {
transformHead({ assets }) { transformHead({ assets }) {
// 相应地调整正则表达式以匹配字体 // 相应地调整正则表达式以匹配字体
const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) { if (myFontFile) {
return [ return [
[ [
@ -251,6 +251,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
{ {
duration: 300, duration: 300,
easing: 'ease-in', easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
} }
) )
@ -288,7 +289,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
</style> </style>
``` ```
Result (**warning!**: flashing colors, sudden movements, bright lights): 结果(**注意!**:画面闪烁、快速闪现、强光刺激):
<details> <details>
<summary>Demo</summary> <summary>Demo</summary>

@ -39,22 +39,6 @@ $ bun add -D vitepress
::: :::
::: details 遇到了 missing peer deps 警告?
如果使用 PNPM会注意到对 `@docsearch/js` 的 missing peer deps 警告。这不会影响 VitePress 运行。如果希望禁止显示此警告,请将以下内容添加到 `package.json`
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
}
}
```
:::
::: tip 注意 ::: tip 注意
VitePress 是仅 ESM 的软件包。不要使用 `require()` 导入它,并确保最新的 `package.json` 包含 `"type": "module"`,或者更改相关文件的文件扩展名,例如 `.vitepress/config.js``.mjs`/`.mts`。更多详情请参考 [Vite 故障排除指南](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only)。此外,在异步 CJS 上下文中,可以使用 `await import('vitepress')` 代替。 VitePress 是仅 ESM 的软件包。不要使用 `require()` 导入它,并确保最新的 `package.json` 包含 `"type": "module"`,或者更改相关文件的文件扩展名,例如 `.vitepress/config.js``.mjs`/`.mts`。更多详情请参考 [Vite 故障排除指南](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only)。此外,在异步 CJS 上下文中,可以使用 `await import('vitepress')` 代替。

@ -255,7 +255,7 @@ Wraps in a `<div class="vp-raw">`
} }
``` ```
它在底层使用 [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config)。你可以像这样传递它的选项: 它在底层使用 [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector)。你可以像这样传递它的选项:
```js ```js
postcssIsolateStyles({ postcssIsolateStyles({

@ -12,7 +12,7 @@ VitePress 是一个[静态站点生成器](https://en.wikipedia.org/wiki/Static_
- **文档** - **文档**
VitePress 附带一个专为技术文档设计的默认主题。你现在正在阅读的这个页面以及 [Vite](https://vitejs.dev/)、[Rollup](https://rollupjs.org/)、[Pinia](https://pinia.vuejs.org/)、[VueUse](https://vueuse.org/)、[Vitest](https://vitest.dev/)、[D3](https://d3js.org/)、[UnoCSS](https://unocss.dev/)、[Iconify](https://iconify.design/) [](https://www.vuetelescope.com/explore?framework.slug=vitepress)文档都是基于这个主题的。 VitePress 附带一个专为技术文档设计的默认主题。你现在正在阅读的这个页面以及 [Vite](https://vitejs.dev/)、[Rollup](https://rollupjs.org/)、[Pinia](https://pinia.vuejs.org/)、[VueUse](https://vueuse.org/)、[Vitest](https://vitest.dev/)、[D3](https://d3js.org/)、[UnoCSS](https://unocss.dev/)、[Iconify](https://iconify.design/) [](https://github.com/search?q=/"vitepress":+/+language:json&type=code)文档都是基于这个主题的。
[Vue.js 官方文档](https://cn.vuejs.org/)也是基于 VitePress 的。但是为了可以在不同的翻译文档之间切换,它自定义了自己的主题。 [Vue.js 官方文档](https://cn.vuejs.org/)也是基于 VitePress 的。但是为了可以在不同的翻译文档之间切换,它自定义了自己的主题。

@ -1,9 +1,6 @@
--- ---
layout: home layout: home
title: VitePress
titleTemplate: 由 Vite 和 Vue 驱动的静态站点生成器
hero: hero:
name: VitePress name: VitePress
text: 由 Vite 和 Vue 驱动的静态站点生成器 text: 由 Vite 和 Vue 驱动的静态站点生成器
@ -19,7 +16,7 @@ hero:
text: GitHub text: GitHub
link: https://github.com/vuejs/vitepress link: https://github.com/vuejs/vitepress
image: image:
src: /vitepress-logo-large.webp src: /vitepress-logo-large.svg
alt: VitePress alt: VitePress
features: features:

@ -43,7 +43,6 @@ vitepress build [root]
| `--base <path>` | public base URL (默认值: `/`) (`string`) | | `--base <path>` | public base URL (默认值: `/`) (`string`) |
| `--target <target>` | 转译目标 (默认值:`"modules"`) (`string`) | | `--target <target>` | 转译目标 (默认值:`"modules"`) (`string`) |
| `--outDir <dir>` | 输出目录 (默认值:`.vitepress/dist`) (`string`) | | `--outDir <dir>` | 输出目录 (默认值:`.vitepress/dist`) (`string`) |
| `--minify [minifier]` | 启用/禁用压缩,或指定要使用的压缩程序 (默认值:`"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | 静态资源 base64 内联阈值(以字节为单位)(默认值:`4096`) (`number`) | | `--assetsInlineLimit <number>` | 静态资源 base64 内联阈值(以字节为单位)(默认值:`4096`) (`number`) |
## `vitepress preview` ## `vitepress preview`

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save