diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..f8cd3d5a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,16 @@ +### Description + + + +### Linked Issues + + + +### Additional Context + + + +--- + +> [!TIP] +> The author of this PR can publish a _preview release_ by commenting `/publish` below. diff --git a/.github/workflows/cr-comment.yml b/.github/workflows/cr-comment.yml new file mode 100644 index 00000000..203b7e11 --- /dev/null +++ b/.github/workflows/cr-comment.yml @@ -0,0 +1,18 @@ +name: Add continuous release label + +on: + issue_comment: + types: [created] + +permissions: + pull-requests: write + +jobs: + label: + if: ${{ github.event.issue.pull_request && (github.event.comment.user.id == github.event.issue.user.id || github.event.comment.author_association == 'MEMBER' || github.event.comment.author_association == 'COLLABORATOR') && startsWith(github.event.comment.body, '/publish') }} + runs-on: ubuntu-latest + + steps: + - run: gh issue edit ${{ github.event.issue.number }} --add-label cr-tracked --repo ${{ github.repository }} + env: + GITHUB_TOKEN: ${{ secrets.CR_PAT }} diff --git a/.github/workflows/cr.yml b/.github/workflows/cr.yml new file mode 100644 index 00000000..a7137f96 --- /dev/null +++ b/.github/workflows/cr.yml @@ -0,0 +1,37 @@ +name: CR + +env: + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1' + +on: + pull_request: + branches: [main] + types: [opened, synchronize, labeled, ready_for_review] + paths-ignore: + - '.github/**' + - '__tests__/**' + - 'art/**' + - 'docs/**' + - '*.md' + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }} + cancel-in-progress: true + +jobs: + release: + if: ${{ !github.event.pull_request.draft && contains(github.event.pull_request.labels.*.name, 'cr-tracked') && !contains(github.event.pull_request.labels.*.name, 'spam') && !contains(github.event.pull_request.labels.*.name, 'invalid') }} + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v3 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + - run: pnpm install + - run: pnpm build + - run: npx pkg-pr-new publish --compact --no-template --pnpm diff --git a/.github/workflows/lock-threads.yml b/.github/workflows/lock-threads.yml index 5dfb3fcc..c76a2acb 100644 --- a/.github/workflows/lock-threads.yml +++ b/.github/workflows/lock-threads.yml @@ -2,12 +2,13 @@ name: Lock Threads on: schedule: - - cron: 0 0 * * * + - cron: 38 4 * * * workflow_dispatch: permissions: issues: write pull-requests: write + discussions: write concurrency: group: lock diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 3c646aa3..f5826155 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -12,4 +12,7 @@ jobs: days-before-close: -1 stale-issue-label: stale stale-pr-label: stale + # action has a bug that keeps removing the stale label from stale PRs + # it's thinking that the PR is updated when the stale label is added + remove-pr-stale-when-updated: false operations-per-run: 1000 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4fdb4296..4d4e59be 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,9 +10,10 @@ on: branches: [main] pull_request: branches: [main] - types: [opened, synchronize, reopened] workflow_dispatch: +permissions: {} + concurrency: group: ${{ github.workflow }}-${{ github.event.number || github.sha }} cancel-in-progress: true @@ -23,7 +24,7 @@ jobs: strategy: matrix: - node_version: [18, 20, 21] + node_version: [18, 20, 22] steps: - name: Checkout diff --git a/.gitignore b/.gitignore index 81c00934..64331052 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ examples-temp node_modules pnpm-global TODOs.md +*.timestamp-*.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index dfe86292..d8ead943 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,113 @@ +## [1.3.3](https://github.com/vuejs/vitepress/compare/v1.3.2...v1.3.3) (2024-08-17) + +### Miscellaneous + +- bump deps ([a20db24](https://github.com/vuejs/vitepress/commit/a20db247822438ac4e0e76bc4a2b4ee2f5d94940)) + +## [1.3.2](https://github.com/vuejs/vitepress/compare/v1.3.1...v1.3.2) (2024-08-05) + +### Bug Fixes + +- multiple cache busting imports causing useData to fail ([2b3e486](https://github.com/vuejs/vitepress/commit/2b3e486ab913ff77707410b9cee3ba6d256ccc95)), closes [#3820](https://github.com/vuejs/vitepress/issues/3820), reverts [#3398](https://github.com/vuejs/vitepress/issues/3398), reopens [#3363](https://github.com/vuejs/vitepress/issues/3363) +- **theme:** excerpt style in LocalSearchBox ([#4050](https://github.com/vuejs/vitepress/issues/4050)) ([2bc0d39](https://github.com/vuejs/vitepress/commit/2bc0d39d5089841986f0988fc9cfe15533d3a0c6)) + +## [1.3.1](https://github.com/vuejs/vitepress/compare/v1.3.0...v1.3.1) (2024-07-14) + +### Bug Fixes + +- don't reopen browser on restart when `vite.server.open` is specified ([6263db1](https://github.com/vuejs/vitepress/commit/6263db170a658ea887ef4b2bfe4b5239a820e0d9)), closes [#4040](https://github.com/vuejs/vitepress/issues/4040) +- **theme/regression:** typo in component props resulting in nested titles not showing in navbar ([01d0d45](https://github.com/vuejs/vitepress/commit/01d0d45292602cbb7de492f0c953ddb239842116)), closes [#4042](https://github.com/vuejs/vitepress/issues/4042) + +# [1.3.0](https://github.com/vuejs/vitepress/compare/v1.2.3...v1.3.0) (2024-07-07) + +### Bug Fixes + +- **build:** don't normalize links containing target or download property ([e24899a](https://github.com/vuejs/vitepress/commit/e24899a073d066486e5f7ae0c47ba6d901d5ae51)), closes [#3947](https://github.com/vuejs/vitepress/issues/3947) +- **build:** respect frontmatter.lastUpdated for pageData.lastUpdated and sitemap generation ([7fcf462](https://github.com/vuejs/vitepress/commit/7fcf462eb8c2be6e72b4426a8211fcd6961e4967)), closes [#3931](https://github.com/vuejs/vitepress/issues/3931) +- **build:** sort pageToHashMap to ensure stable assets ([e302328](https://github.com/vuejs/vitepress/commit/e302328a4ce3242cbfb7112e856840b7346aa16a)), closes [#4016](https://github.com/vuejs/vitepress/issues/4016) +- **client:** do nothing on anchor elements with empty href ([6461f5d](https://github.com/vuejs/vitepress/commit/6461f5d42b3bfed1d7959e1167fc77f61d08f314)), closes [#3950](https://github.com/vuejs/vitepress/issues/3950) +- don't do git log on non-existent file ([387acf7](https://github.com/vuejs/vitepress/commit/387acf71aa351e23ca3402713020a3571ad17155)), closes [#4008](https://github.com/vuejs/vitepress/issues/4008) +- don't reopen browser on restart ([d837e82](https://github.com/vuejs/vitepress/commit/d837e82bc8bde63df737be2a1290a2e70c8a0bf3)), closes [#4001](https://github.com/vuejs/vitepress/issues/4001) +- properly handle svg anchor elements ([b785bd6](https://github.com/vuejs/vitepress/commit/b785bd6ab3b5dd909aa955dc9e03b08e66b76294)) +- **theme:** add styles for h4 too ([b54d7b0](https://github.com/vuejs/vitepress/commit/b54d7b0d7cd1257bcadd25f9b69cba21d0a3dff6)) +- **theme:** deep watch sidebar groups and force render on match change ([97f9469](https://github.com/vuejs/vitepress/commit/97f9469b6d4eb7ba9de9a1111986581d1f704ec3)), closes [#3613](https://github.com/vuejs/vitepress/issues/3613) +- **theme:** dim color for all text like elements inside blockquotes ([5d3ed87](https://github.com/vuejs/vitepress/commit/5d3ed87f8530134fa709681ebadb2f3cfc68680e)), closes [#3929](https://github.com/vuejs/vitepress/issues/3929) +- **theme:** force update title attribute on hydration ([d348da7](https://github.com/vuejs/vitepress/commit/d348da770c2a68993d1a40d1c0223e42a681057a)), closes [#4004](https://github.com/vuejs/vitepress/issues/4004) +- **theme:** show filled nav bar when nav screen is open ([0fc70e2](https://github.com/vuejs/vitepress/commit/0fc70e2d0c29c92a1dceba035295a3fac84ffc00)) + +### Features + +- allow using components in navigation bar ([#4000](https://github.com/vuejs/vitepress/issues/4000)) ([fa87d81](https://github.com/vuejs/vitepress/commit/fa87d8150d8185fa8a22cd6b6e762632b83f8231)) +- **cli/init:** allow passing target dir as command argument ([#3948](https://github.com/vuejs/vitepress/issues/3948)) ([99053ba](https://github.com/vuejs/vitepress/commit/99053baea7eb6aa62a11a2cfd4b1e6e60311dd63)) +- **markdown:** support including specific regions from markdown files ([#3978](https://github.com/vuejs/vitepress/issues/3978)) ([143b1e9](https://github.com/vuejs/vitepress/commit/143b1e91f3696507d33666ec5847e7b64a771bcf)) +- support `force-auto` as an option for appearance ([1e8bb48](https://github.com/vuejs/vitepress/commit/1e8bb48bc2891ea388bf0b9edd2f5b612bb1e85d)), closes [#3946](https://github.com/vuejs/vitepress/issues/3946) +- **theme:** export VPHomeContent ([#3960](https://github.com/vuejs/vitepress/issues/3960)) ([8aa6ccb](https://github.com/vuejs/vitepress/commit/8aa6ccbe32655f76c390d15568f69f83d079385d)), closes [#3954](https://github.com/vuejs/vitepress/issues/3954) + +## [1.2.3](https://github.com/vuejs/vitepress/compare/v1.2.2...v1.2.3) (2024-06-04) + +### Bug Fixes + +- **theme,a11y:** handle overflow on long mathematical equation and make tables focusable ([#3932](https://github.com/vuejs/vitepress/issues/3932)) (closes [#3914](https://github.com/vuejs/vitepress/issues/3914)) ([afc611d](https://github.com/vuejs/vitepress/commit/afc611d399d2780550ae04caa0e73e1c0c69a680)) +- **types:** wrong types generated for markdown-it > mdurl ([48ca76c](https://github.com/vuejs/vitepress/commit/48ca76c523d9b979a678d52447f5ce324799e47f)), closes [#3935](https://github.com/vuejs/vitepress/issues/3935) + +## [1.2.2](https://github.com/vuejs/vitepress/compare/v1.2.1...v1.2.2) (2024-05-21) + +### Bug Fixes + +- dont escape ampersand twice in title ([7ea3572](https://github.com/vuejs/vitepress/commit/7ea357256c855ae0a9a142c14bbd5e7d344ef865)) + +## [1.2.1](https://github.com/vuejs/vitepress/compare/v1.2.0...v1.2.1) (2024-05-21) + +### Bug Fixes + +- **a11y:** make code blocks accessible with keyboard ([#3902](https://github.com/vuejs/vitepress/issues/3902)) ([cb308b9](https://github.com/vuejs/vitepress/commit/cb308b9295e1e661c2c72fa4229b5c7d83278d49)) +- escape title properly in build ([49b1233](https://github.com/vuejs/vitepress/commit/49b1233378436054c07a6ef646d0029096124021)) +- **theme:** remove unnecessary navigation role on nav element ([af4717d](https://github.com/vuejs/vitepress/commit/af4717d6820233a011200d44abba53d0f66bfad3)) + +# [1.2.0](https://github.com/vuejs/vitepress/compare/v1.1.4...v1.2.0) (2024-05-18) + +### Bug Fixes + +- **build:** show file info on error ([f0debd2](https://github.com/vuejs/vitepress/commit/f0debd20f48ab7eb58cfd142147531509d6c0209)) +- **dev:** match dev and prod routing behavior ([#3837](https://github.com/vuejs/vitepress/issues/3837)) ([b360ac8](https://github.com/vuejs/vitepress/commit/b360ac88df3bfd60e3498cc19066c0c90261ee4f)) +- **markdown:** entities and escapes not working properly ([#3882](https://github.com/vuejs/vitepress/issues/3882)) ([d5dbd70](https://github.com/vuejs/vitepress/commit/d5dbd704ceb215ebf3ce9b23deec6e6c90634f0a)) +- render 404 page completely on client to infer locale from browser path ([#3858](https://github.com/vuejs/vitepress/issues/3858)) ([728cb15](https://github.com/vuejs/vitepress/commit/728cb15677f4f84b33bed6bb2f70f47600ea1057)) +- **style:** prefer YaHei over DengXian ([f0a37b4](https://github.com/vuejs/vitepress/commit/f0a37b4b8445ec914700df054c0897721382e5b1)) +- **theme/regression:** custom font not applying in Chinese docs because of specificity ([fa2f38a](https://github.com/vuejs/vitepress/commit/fa2f38a0c3bd121dcb7e07420566087c19b10f96)), closes [#3864](https://github.com/vuejs/vitepress/issues/3864) +- **theme:** external link icon not visible for target \_blank links ([d08eeed](https://github.com/vuejs/vitepress/commit/d08eeed89726572f7ea341df59864cc72716751c)), closes [#3327](https://github.com/vuejs/vitepress/issues/3327) +- **theme:** fix invalid vp-offset in ssr ([9794877](https://github.com/vuejs/vitepress/commit/9794877347140c7b4955d735cd8867c260a5089d)) + +### Features + +- **build/i18n:** support customizing copy code button's tooltip text ([#3854](https://github.com/vuejs/vitepress/issues/3854)) ([ed6ada7](https://github.com/vuejs/vitepress/commit/ed6ada7a688c466920f3e0ef33b7176b8eb01eee)) +- **build:** add localeIndex to md.env ([#3862](https://github.com/vuejs/vitepress/issues/3862)) ([0cbb469](https://github.com/vuejs/vitepress/commit/0cbb469842d74381ad56d44b7975f34c405b78f8)) + +## [1.1.4](https://github.com/vuejs/vitepress/compare/v1.1.3...v1.1.4) (2024-04-27) + +### Bug Fixes + +- **dev:** multiple server instances being created when editing config too quickly ([#3835](https://github.com/vuejs/vitepress/issues/3835)) ([729a890](https://github.com/vuejs/vitepress/commit/729a890669c363895cfac39ece046926cad36d01)) +- **theme/a11y:** add unique name to footer prev / next navigation landmark ([e60c101](https://github.com/vuejs/vitepress/commit/e60c101e50fa56d4cd54d434c5628cc7e2231318)) +- **theme/a11y:** remove duplicate assistive text from outline nav ([#3803](https://github.com/vuejs/vitepress/issues/3803)) ([733d986](https://github.com/vuejs/vitepress/commit/733d986a84f614484b04235546dc4cda0769e833)) +- **theme/i18n:** 404 page not showing localized text ([#3833](https://github.com/vuejs/vitepress/issues/3833)) ([cc11b8e](https://github.com/vuejs/vitepress/commit/cc11b8e41ec481320b03902bdc307d479a8ba838)) +- **theme:** disable keypress effect on search button ([ccc37bb](https://github.com/vuejs/vitepress/commit/ccc37bb80e4147b9ab91b0f5d7dfae9d51533460)) +- **theme:** don't use Chinese quotes on non-Chinese documents ([#3834](https://github.com/vuejs/vitepress/issues/3834)) ([75115f4](https://github.com/vuejs/vitepress/commit/75115f4f8223d67dab2dc82fadaf2941aabf6330)) +- **theme:** leaking event listener when going back/forward on Safari on iOS ([#3658](https://github.com/vuejs/vitepress/issues/3658)) ([#3671](https://github.com/vuejs/vitepress/issues/3671)) ([1a72181](https://github.com/vuejs/vitepress/commit/1a72181c06d78e5e6f293e3f6abdb15caa4d2f53)) + +## [1.1.3](https://github.com/vuejs/vitepress/compare/v1.1.1...v1.1.3) (2024-04-18) + +### Bug Fixes + +- **build/regression:** markdown backslash escapes not working ([d02d1e9](https://github.com/vuejs/vitepress/commit/d02d1e923aacdb1e8061a3f76af30e8a13518277)), closes [#3808](https://github.com/vuejs/vitepress/issues/3808) + +## [1.1.1](https://github.com/vuejs/vitepress/compare/v1.1.0...v1.1.1) (2024-04-18) + +### Bug Fixes + +- **client:** don't reload page on hash change ([#3777](https://github.com/vuejs/vitepress/issues/3777)) ([74b725a](https://github.com/vuejs/vitepress/commit/74b725a224438ef776fed25ee82274429d94ac83)) +- let vue compiler handle entity decoding ([f86ac56](https://github.com/vuejs/vitepress/commit/f86ac56b78da76f3061e6537b897bb13c1ed802d)) +- hot updating config file suppresses error logs ([#3592](https://github.com/vuejs/vitepress/issues/3592)) ([cd5adf3](https://github.com/vuejs/vitepress/commit/cd5adf3011d677263c93ce6f8066aaa7870b1dfc)) + # [1.1.0](https://github.com/vuejs/vitepress/compare/v1.0.2...v1.1.0) (2024-04-09) ### Bug Fixes diff --git a/__tests__/e2e/.vitepress/config.ts b/__tests__/e2e/.vitepress/config.ts index e4e503a6..65f845ab 100644 --- a/__tests__/e2e/.vitepress/config.ts +++ b/__tests__/e2e/.vitepress/config.ts @@ -1,5 +1,73 @@ import { defineConfig, type DefaultTheme } from 'vitepress' +const nav: DefaultTheme.Config['nav'] = [ + { + text: 'Home', + link: '/' + }, + { + text: 'API Reference', + items: [ + { + text: 'Example', + link: '/home.html' + }, + { + component: 'ApiPreference', + props: { + options: ['JavaScript', 'TypeScript', 'Flow'], + defaultOption: 'TypeScript' + } + }, + { + component: 'ApiPreference', + props: { + options: ['Options', 'Composition'], + defaultOption: 'Composition' + } + } + ] + }, + { + component: 'NavVersion', + props: { + versions: [ + { + text: 'v1.x', + link: '/' + }, + { + text: 'v0.x', + link: '/v0.x/' + } + ] + } + }, + { + text: 'Nested', + items: [ + { + text: 'Level 1 - 1', + items: [ + { + text: 'Level 2 - 1', + link: '/nested/level1-1/level2-1' + } + ] + }, + { + text: 'Level 1 - 2', + items: [ + { + text: 'Level 2 - 2', + link: '/nested/level1-2/level2-2' + } + ] + } + ] + } +] + const sidebar: DefaultTheme.Config['sidebar'] = { '/': [ { @@ -92,6 +160,7 @@ export default defineConfig({ } }, themeConfig: { + nav, sidebar, search: { provider: 'local', diff --git a/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue b/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue new file mode 100644 index 00000000..12207764 --- /dev/null +++ b/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue @@ -0,0 +1,83 @@ + + + + + diff --git a/__tests__/e2e/.vitepress/theme/components/NavVersion.vue b/__tests__/e2e/.vitepress/theme/components/NavVersion.vue new file mode 100644 index 00000000..d256e3d2 --- /dev/null +++ b/__tests__/e2e/.vitepress/theme/components/NavVersion.vue @@ -0,0 +1,50 @@ + + + + + diff --git a/__tests__/e2e/.vitepress/theme/index.ts b/__tests__/e2e/.vitepress/theme/index.ts new file mode 100644 index 00000000..d2629777 --- /dev/null +++ b/__tests__/e2e/.vitepress/theme/index.ts @@ -0,0 +1,12 @@ +import type { Theme } from 'vitepress' +import DefaultTheme from 'vitepress/theme' +import ApiPreference from './components/ApiPreference.vue' +import NavVersion from './components/NavVersion.vue' + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('ApiPreference', ApiPreference) + app.component('NavVersion', NavVersion) + } +} satisfies Theme diff --git a/__tests__/e2e/markdown-extensions/index.md b/__tests__/e2e/markdown-extensions/index.md index 47246c18..855803f2 100644 --- a/__tests__/e2e/markdown-extensions/index.md +++ b/__tests__/e2e/markdown-extensions/index.md @@ -197,6 +197,22 @@ export default config +## Markdown At File Region Snippet + + + +## Markdown At File Range Region Snippet + + + +## Markdown At File Range Region Snippet without start + + + +## Markdown At File Range Region Snippet without end + + + ## Image Lazy Loading ![vitepress logo](/vitepress.png) \ No newline at end of file diff --git a/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts b/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts index 23b8b1a0..e49a137f 100644 --- a/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts +++ b/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts @@ -65,7 +65,7 @@ describe('Table of Contents', () => { test('render toc', async () => { const items = page.locator('#table-of-contents + nav ul li') const count = await items.count() - expect(count).toBe(36) + expect(count).toBe(44) }) }) @@ -275,6 +275,26 @@ describe('Markdown File Inclusion', () => { expect(trim(await p.nth(1).textContent())).toBe('This is after region') }) + test('support markdown region snippet', async () => { + const h2 = page.locator('#markdown-at-file-region-snippet + h2') + expect(await h2.getAttribute('id')).toBe('region-snippet') + + const line = page.locator('#markdown-at-file-range-region-snippet + h2') + expect(await line.getAttribute('id')).toBe('range-region-line-2') + + const lineWithoutStart = page.locator( + '#markdown-at-file-range-region-snippet-without-start + h2' + ) + expect(await lineWithoutStart.getAttribute('id')).toBe( + 'range-region-line-1' + ) + + const lineWithoutEnd = page.locator( + '#markdown-at-file-range-region-snippet-without-end + h2' + ) + expect(await lineWithoutEnd.getAttribute('id')).toBe('range-region-line-3') + }) + test('ignore frontmatter if range is not specified', async () => { const p = page.locator('.vp-doc') expect(await p.textContent()).not.toContain('title') diff --git a/__tests__/e2e/markdown-extensions/region-include.md b/__tests__/e2e/markdown-extensions/region-include.md new file mode 100644 index 00000000..4daeb7ff --- /dev/null +++ b/__tests__/e2e/markdown-extensions/region-include.md @@ -0,0 +1,13 @@ + + + +## Range Region Line 1 + +## Range Region Line 2 + +## Range Region Line 3 + + + +## Region Snippet + diff --git a/docs/.vitepress/config/es.ts b/docs/.vitepress/config/es.ts new file mode 100644 index 00000000..d924c5b8 --- /dev/null +++ b/docs/.vitepress/config/es.ts @@ -0,0 +1,215 @@ +import { createRequire } from 'module' +import { defineConfig, type DefaultTheme } from 'vitepress' + +const require = createRequire(import.meta.url) +const pkg = require('vitepress/package.json') + +export const es = defineConfig({ + lang: 'es-CO', + description: 'Generador de Sitios Estaticos desarrollado con Vite y Vue.', + + themeConfig: { + nav: nav(), + + sidebar: { + '/es/guide/': { base: '/es/guide/', items: sidebarGuide() }, + '/es/reference/': { base: '/es/reference/', items: sidebarReference() } + }, + + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'Editar esta página en GitHub' + }, + + footer: { + message: 'Liberado bajo la licencia MIT', + copyright: `Derechos reservados © 2019-${new Date().getFullYear()} Evan You` + }, + + docFooter: { + prev: 'Anterior', + next: 'Siguiente' + }, + + outline: { + label: 'En esta página' + }, + + lastUpdated: { + text: 'Actualizado en', + formatOptions: { + dateStyle: 'short', + timeStyle: 'medium' + } + }, + + langMenuLabel: 'Cambiar Idioma', + returnToTopLabel: 'Volver arriba', + sidebarMenuLabel: 'Menu Lateral', + darkModeSwitchLabel: 'Tema Oscuro', + lightModeSwitchTitle: 'Cambiar a modo claro', + darkModeSwitchTitle: 'Cambiar a modo oscuro' + } +}) + +function nav(): DefaultTheme.NavItem[] { + return [ + { + text: 'Guia', + link: '/es/guide/what-is-vitepress', + activeMatch: '/es/guide/' + }, + { + text: 'Referencia', + link: '/es/reference/site-config', + activeMatch: '/es/reference/' + }, + { + text: pkg.version, + items: [ + { + text: 'Registro de cambios', + link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' + }, + { + text: 'Contribuir', + link: 'https://github.com/vuejs/vitepress/blob/main/.github/contributing.md' + } + ] + } + ] +} + +function sidebarGuide(): DefaultTheme.SidebarItem[] { + return [ + { + text: 'Introducción', + collapsed: false, + items: [ + { text: 'Qué es VitePress?', link: 'what-is-vitepress' }, + { text: 'Iniciando', link: 'getting-started' }, + { text: 'Enrutamiento', link: 'routing' }, + { text: 'Despliegue', link: 'deploy' } + ] + }, + { + text: 'Escribiendo', + collapsed: false, + items: [ + { text: 'Extensiones Markdown', link: 'markdown' }, + { text: 'Manejo de assets', link: 'asset-handling' }, + { text: 'Frontmatter', link: 'frontmatter' }, + { text: 'Usando Vue en Markdown', link: 'using-vue' }, + { text: 'Internacionalización', link: 'i18n' } + ] + }, + { + text: 'Pesonalización', + collapsed: false, + items: [ + { text: 'Usando un tema personalizado', link: 'custom-theme' }, + { + text: 'Extendiendo el tema por defecto', + link: 'extending-default-theme' + }, + { + text: 'Carga de datos en tiempo de compilación', + link: 'data-loading' + }, + { text: 'Compatibilidad SSR', link: 'ssr-compat' }, + { text: 'Conectando a un CMS', link: 'cms' } + ] + }, + { + text: 'Experimental', + collapsed: false, + items: [ + { text: 'Modo MPA', link: 'mpa-mode' }, + { text: 'Generación de Sitemap', link: 'sitemap-generation' } + ] + }, + { + text: 'Configuración y Referencia del API', + base: '/es/reference/', + link: 'site-config' + } + ] +} + +function sidebarReference(): DefaultTheme.SidebarItem[] { + return [ + { + text: 'Referencia', + items: [ + { text: 'Configuración del sitio', link: 'site-config' }, + { text: 'Configuración Frontmatter', link: 'frontmatter-config' }, + { text: 'API de tiempo de ejecución', link: 'runtime-api' }, + { text: 'CLI', link: 'cli' }, + { + text: 'Tema por defecto', + base: '/es/reference/default-theme-', + items: [ + { text: 'Visión general', link: 'config' }, + { text: 'Navegación', link: 'nav' }, + { text: 'Barra Lateral', link: 'sidebar' }, + { text: 'Página Inicial', link: 'home-page' }, + { text: 'Pie de página', link: 'footer' }, + { text: 'Layout', link: 'layout' }, + { text: 'Distintivo', link: 'badge' }, + { text: 'Página del equipo', link: 'team-page' }, + { text: 'Links Anterior / Siguiente', link: 'prev-next-links' }, + { text: 'Editar Link', link: 'edit-link' }, + { text: 'Sello temporal de actualización', link: 'last-updated' }, + { text: 'Busqueda', link: 'search' }, + { text: 'Carbon Ads', link: 'carbon-ads' } + ] + } + ] + } + ] +} + +export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { + es: { + placeholder: 'Buscar documentos', + translations: { + button: { + buttonText: 'Buscar', + buttonAriaLabel: 'Buscar' + }, + modal: { + searchBox: { + resetButtonTitle: 'Limpiar búsqueda', + resetButtonAriaLabel: 'Limpiar búsqueda', + cancelButtonText: 'Cancelar', + cancelButtonAriaLabel: 'Cancelar' + }, + startScreen: { + recentSearchesTitle: 'Historial de búsqueda', + noRecentSearchesText: 'Ninguna búsqueda reciente', + saveRecentSearchButtonTitle: 'Guardar en el historial de búsqueda', + removeRecentSearchButtonTitle: 'Borrar del historial de búsqueda', + favoriteSearchesTitle: 'Favoritos', + removeFavoriteSearchButtonTitle: 'Borrar de favoritos' + }, + errorScreen: { + titleText: 'No fue posible obtener resultados', + helpText: 'Verifique su conexión de red' + }, + footer: { + selectText: 'Seleccionar', + navigateText: 'Navegar', + closeText: 'Cerrar', + searchByText: 'Busqueda por' + }, + noResultsScreen: { + noResultsText: 'No fue posible encontrar resultados', + suggestedQueryText: 'Puede intentar una nueva búsqueda', + reportMissingResultsText: + 'Deberian haber resultados para esa consulta?', + reportMissingResultsLinkText: 'Click para enviar feedback' + } + } + } + } +} diff --git a/docs/.vitepress/config/index.ts b/docs/.vitepress/config/index.ts index df198ad4..2715ccdc 100644 --- a/docs/.vitepress/config/index.ts +++ b/docs/.vitepress/config/index.ts @@ -4,6 +4,8 @@ import { en } from './en' import { zh } from './zh' import { pt } from './pt' import { ru } from './ru' +import { es } from './es' +import { ko } from './ko' export default defineConfig({ ...shared, @@ -12,6 +14,7 @@ export default defineConfig({ zh: { label: '简体中文', ...zh }, pt: { label: 'Português', ...pt }, ru: { label: 'Русский', ...ru }, - ko: { label: '한국어', lang: 'ko-KR', link: 'https://vitepress.vuejs.kr/' } + es: { label: 'Español', ...es }, + ko: { label: '한국어', ...ko } } }) diff --git a/docs/.vitepress/config/ko.ts b/docs/.vitepress/config/ko.ts new file mode 100644 index 00000000..906669d3 --- /dev/null +++ b/docs/.vitepress/config/ko.ts @@ -0,0 +1,252 @@ +import { createRequire } from 'module' +import { defineConfig, type DefaultTheme } from 'vitepress' + +const require = createRequire(import.meta.url) +const pkg = require('vitepress/package.json') + +export const ko = defineConfig({ + lang: 'ko-KR', + description: 'Vite 및 Vue 기반 정적 사이트 생성기.', + + themeConfig: { + nav: nav(), + + sidebar: { + '/ko/guide/': { base: '/ko/guide/', items: sidebarGuide() }, + '/ko/reference/': { base: '/ko/reference/', items: sidebarReference() } + }, + + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: '이 페이지 편집 제안하기' + }, + + footer: { + message: 'Released under the MIT License.', + copyright: 'Copyright © 2019-present Evan You' + }, + + docFooter: { + prev: '이전', + next: '다음' + }, + + outline: { + label: '이 페이지 목차' + }, + + lastUpdated: { + text: '업데이트 날짜' + }, + + langMenuLabel: '언어 변경', + returnToTopLabel: '맨 위로 돌아가기', + sidebarMenuLabel: '사이드바 메뉴', + darkModeSwitchLabel: '다크 모드', + lightModeSwitchTitle: '라이트 모드로 변경', + darkModeSwitchTitle: '다크 모드로 변경' + } +}) + +function nav(): DefaultTheme.NavItem[] { + return [ + { + text: '가이드', + link: '/ko/guide/what-is-vitepress', + activeMatch: '/ko/guide/' + }, + { + text: '레퍼런스', + link: '/ko/reference/site-config', + activeMatch: '/ko/reference/' + }, + { + text: pkg.version, + items: [ + { + text: '변경 로그', + link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' + }, + { + text: '기여', + link: 'https://github.com/vuejs/vitepress/blob/main/.github/contributing.md' + } + ] + } + ] +} + +function sidebarGuide(): DefaultTheme.SidebarItem[] { + return [ + { + text: '소개', + collapsed: false, + items: [ + { + text: 'VitePress란 무엇인가?', + link: 'what-is-vitepress' + }, + { + text: '시작하기', + link: 'getting-started' + }, + { + text: '라우팅', + link: 'routing' + }, + { + text: '배포하기', + link: 'deploy' + } + ] + }, + { + text: '글쓰기', + collapsed: false, + items: [ + { + text: '마크다운 확장 기능', + link: 'markdown' + }, + { + text: '에셋 핸들링', + link: 'asset-handling' + }, + { + text: '전문(Front-matter)', + link: 'frontmatter' + }, + { + text: '마크다운에서 Vue 사용하기', + link: 'using-vue' + }, + { + text: 'i18n', + link: 'i18n' + } + ] + }, + { + text: '커스텀', + collapsed: false, + items: [ + { + text: '커스텀 테마 사용하기', + link: 'custom-theme' + }, + { + text: '기본 테마 확장하기', + link: 'extending-default-theme' + }, + { + text: '빌드할 때 데이터 로딩하기', + link: 'data-loading' + }, + { + text: 'SSR 호환성', + link: 'ssr-compat' + }, + { + text: 'CMS 연결하기', + link: 'cms' + } + ] + }, + { + text: '실험적인', + collapsed: false, + items: [ + { + text: 'MPA 모드', + link: 'mpa-mode' + }, + { + text: '사이트맵 생성', + link: 'sitemap-generation' + } + ] + }, + { + text: '구성 & API 레퍼런스', + base: '/ko/reference/', + link: 'site-config' + } + ] +} + +function sidebarReference(): DefaultTheme.SidebarItem[] { + return [ + { + text: '레퍼런스', + items: [ + { text: '사이트 구성', link: 'site-config' }, + { text: '전문(front-matter) 구성', link: 'frontmatter-config' }, + { text: '런타임 API', link: 'runtime-api' }, + { text: 'CLI', link: 'cli' }, + { + text: '기본 테마', + base: '/ko/reference/default-theme-', + items: [ + { text: '개요', link: 'config' }, + { text: '네비게이션 바', link: 'nav' }, + { text: '사이드바', link: 'sidebar' }, + { text: '홈 페이지', link: 'home-page' }, + { text: '푸터', link: 'footer' }, + { text: '레이아웃', link: 'layout' }, + { text: '배지(badge)', link: 'badge' }, + { text: '팀 페이지', link: 'team-page' }, + { text: '이전/다음 링크', link: 'prev-next-links' }, + { text: '편집 링크', link: 'edit-link' }, + { text: '마지막 업데이트 날짜', link: 'last-updated' }, + { text: '검색', link: 'search' }, + { text: '카본 광고', link: 'carbon-ads' } + ] + } + ] + } + ] +} + +export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { + ko: { + placeholder: '문서 검색', + translations: { + button: { + buttonText: '검색', + buttonAriaLabel: '검색' + }, + modal: { + searchBox: { + resetButtonTitle: '검색 지우기', + resetButtonAriaLabel: '검색 지우기', + cancelButtonText: '취소', + cancelButtonAriaLabel: '취소' + }, + startScreen: { + recentSearchesTitle: '검색 기록', + noRecentSearchesText: '최근 검색 없음', + saveRecentSearchButtonTitle: '검색 기록에 저장', + removeRecentSearchButtonTitle: '검색 기록에서 삭제', + favoriteSearchesTitle: '즐겨찾기', + removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제' + }, + errorScreen: { + titleText: '결과를 가져올 수 없습니다', + helpText: '네트워크 연결을 확인하세요' + }, + footer: { + selectText: '선택', + navigateText: '탐색', + closeText: '닫기', + searchByText: '검색 기준' + }, + noResultsScreen: { + noResultsText: '결과를 찾을 수 없습니다', + suggestedQueryText: '새로운 검색을 시도할 수 있습니다', + reportMissingResultsText: '해당 검색어에 대한 결과가 있어야 합니까?', + reportMissingResultsLinkText: '피드백 보내기 클릭' + } + } + } + } +} diff --git a/docs/.vitepress/config/shared.ts b/docs/.vitepress/config/shared.ts index 77386002..65907247 100644 --- a/docs/.vitepress/config/shared.ts +++ b/docs/.vitepress/config/shared.ts @@ -2,10 +2,16 @@ import { defineConfig } from 'vitepress' import { search as zhSearch } from './zh' import { search as ptSearch } from './pt' import { search as ruSearch } from './ru' +import { search as esSearch } from './es' +import { search as koSearch } from './ko' export const shared = defineConfig({ title: 'VitePress', + rewrites: { + 'en/:rest*': ':rest*' + }, + lastUpdated: true, cleanUrls: true, metaChunk: true, @@ -56,7 +62,13 @@ export const shared = defineConfig({ appId: '8J64VVRP8K', apiKey: 'a18e2f4cc5665f6602c5631fd868adfd', indexName: 'vitepress', - locales: { ...zhSearch, ...ptSearch, ...ruSearch } + locales: { + ...zhSearch, + ...ptSearch, + ...ruSearch, + ...esSearch, + ...koSearch + } } }, diff --git a/docs/guide/asset-handling.md b/docs/en/guide/asset-handling.md similarity index 100% rename from docs/guide/asset-handling.md rename to docs/en/guide/asset-handling.md diff --git a/docs/guide/cms.md b/docs/en/guide/cms.md similarity index 100% rename from docs/guide/cms.md rename to docs/en/guide/cms.md diff --git a/docs/guide/custom-theme.md b/docs/en/guide/custom-theme.md similarity index 100% rename from docs/guide/custom-theme.md rename to docs/en/guide/custom-theme.md diff --git a/docs/guide/data-loading.md b/docs/en/guide/data-loading.md similarity index 100% rename from docs/guide/data-loading.md rename to docs/en/guide/data-loading.md diff --git a/docs/guide/deploy.md b/docs/en/guide/deploy.md similarity index 97% rename from docs/guide/deploy.md rename to docs/en/guide/deploy.md index 01eeafd3..852fb868 100644 --- a/docs/guide/deploy.md +++ b/docs/en/guide/deploy.md @@ -198,7 +198,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f ### GitLab Pages -1. Set `outDir` in VitePress config to `../public`. Configure `base` option to `'//'` if you want to deploy to `https://.gitlab.io//`. +1. Set `outDir` in VitePress config to `../public`. Configure `base` option to `'//'` if you want to deploy to `https://.gitlab.io//`. You don't need `base` if you're deploying to custom domain, user or group pages, or have "Use unique domain" setting enabled in GitLab. 2. Create a file named `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content: @@ -286,7 +286,7 @@ Refer [Creating and Deploying a VitePress App To Edgio](https://docs.edg.io/guid ### Kinsta Static Site Hosting -You can deploy your Vitepress website on [Kinsta](https://kinsta.com/static-site-hosting/) by following these [instructions](https://kinsta.com/docs/vitepress-static-site-example/). +You can deploy your VitePress website on [Kinsta](https://kinsta.com/static-site-hosting/) by following these [instructions](https://kinsta.com/docs/vitepress-static-site-example/). ### Stormkit diff --git a/docs/guide/extending-default-theme.md b/docs/en/guide/extending-default-theme.md similarity index 100% rename from docs/guide/extending-default-theme.md rename to docs/en/guide/extending-default-theme.md diff --git a/docs/guide/frontmatter.md b/docs/en/guide/frontmatter.md similarity index 100% rename from docs/guide/frontmatter.md rename to docs/en/guide/frontmatter.md diff --git a/docs/guide/getting-started.md b/docs/en/guide/getting-started.md similarity index 99% rename from docs/guide/getting-started.md rename to docs/en/guide/getting-started.md index 7d7c577e..7a023895 100644 --- a/docs/guide/getting-started.md +++ b/docs/en/guide/getting-started.md @@ -29,6 +29,10 @@ $ pnpm add -D vitepress $ yarn add -D vitepress ``` +```sh [yarn (pnp)] +$ yarn add -D vitepress vue +``` + ```sh [bun] $ bun add -D vitepress ``` diff --git a/docs/guide/i18n.md b/docs/en/guide/i18n.md similarity index 100% rename from docs/guide/i18n.md rename to docs/en/guide/i18n.md diff --git a/docs/guide/markdown.md b/docs/en/guide/markdown.md similarity index 96% rename from docs/guide/markdown.md rename to docs/en/guide/markdown.md index d5b68de6..9eb4c0e7 100644 --- a/docs/guide/markdown.md +++ b/docs/en/guide/markdown.md @@ -255,7 +255,7 @@ Wraps in a
} ``` - It uses [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) under the hood. You can pass its options like this: + It uses [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector) under the hood. You can pass its options like this: ```js postcssIsolateStyles({ @@ -834,6 +834,43 @@ Can be created using `.foorc.json`. The format of the selected line range can be: `{3,}`, `{,10}`, `{1,10}` +You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/codebasics#_folding) to only include the corresponding part of the code file. You can provide a custom region name after a `#` following the filepath: + +**Input** + +```md +# Docs + +## Basics + + + +``` + +**Part file** (`parts/basics.md`) + +```md + +## Usage Line 1 + +## Usage Line 2 + +## Usage Line 3 + +``` + +**Equivalent code** + +```md +# Docs + +## Basics + +## Usage Line 1 + +## Usage Line 3 +``` + ::: warning Note that this does not throw errors if your file is not present. Hence, when using this feature make sure that the contents are being rendered as expected. ::: diff --git a/docs/guide/migration-from-vitepress-0.md b/docs/en/guide/migration-from-vitepress-0.md similarity index 100% rename from docs/guide/migration-from-vitepress-0.md rename to docs/en/guide/migration-from-vitepress-0.md diff --git a/docs/guide/migration-from-vuepress.md b/docs/en/guide/migration-from-vuepress.md similarity index 100% rename from docs/guide/migration-from-vuepress.md rename to docs/en/guide/migration-from-vuepress.md diff --git a/docs/guide/mpa-mode.md b/docs/en/guide/mpa-mode.md similarity index 100% rename from docs/guide/mpa-mode.md rename to docs/en/guide/mpa-mode.md diff --git a/docs/guide/routing.md b/docs/en/guide/routing.md similarity index 100% rename from docs/guide/routing.md rename to docs/en/guide/routing.md diff --git a/docs/guide/sitemap-generation.md b/docs/en/guide/sitemap-generation.md similarity index 84% rename from docs/guide/sitemap-generation.md rename to docs/en/guide/sitemap-generation.md index 7d891428..4d52984f 100644 --- a/docs/guide/sitemap-generation.md +++ b/docs/en/guide/sitemap-generation.md @@ -3,13 +3,11 @@ VitePress comes with out-of-the-box support for generating a `sitemap.xml` file for your site. To enable it, add the following to your `.vitepress/config.js`: ```ts -import { defineConfig } from 'vitepress' - -export default defineConfig({ +export default { sitemap: { hostname: 'https://example.com' } -}) +} ``` To have `` tags in your `sitemap.xml`, you can enable the [`lastUpdated`](../reference/default-theme-last-updated) option. @@ -19,14 +17,23 @@ To have `` tags in your `sitemap.xml`, you can enable the [`lastUpdated Sitemap support is powered by the [`sitemap`](https://www.npmjs.com/package/sitemap) module. You can pass any options supported by it to the `sitemap` option in your config file. These will be passed directly to the `SitemapStream` constructor. Refer to the [`sitemap` documentation](https://www.npmjs.com/package/sitemap#options-you-can-pass) for more details. Example: ```ts -import { defineConfig } from 'vitepress' - -export default defineConfig({ +export default { sitemap: { hostname: 'https://example.com', lastmodDateOnly: false } -}) +} +``` + +If you're using `base` in your config, you should append it to the `hostname` option: + +```ts +export default { + base: '/my-site/', + sitemap: { + hostname: 'https://example.com/my-site/' + } +} ``` ## `transformItems` Hook @@ -34,9 +41,7 @@ export default defineConfig({ You can use the `sitemap.transformItems` hook to modify the sitemap items before they are written to the `sitemap.xml` file. This hook is called with an array of sitemap items and expects an array of sitemap items to be returned. Example: ```ts -import { defineConfig } from 'vitepress' - -export default defineConfig({ +export default { sitemap: { hostname: 'https://example.com', transformItems: (items) => { @@ -49,5 +54,5 @@ export default defineConfig({ return items } } -}) +} ``` diff --git a/docs/guide/ssr-compat.md b/docs/en/guide/ssr-compat.md similarity index 100% rename from docs/guide/ssr-compat.md rename to docs/en/guide/ssr-compat.md diff --git a/docs/guide/using-vue.md b/docs/en/guide/using-vue.md similarity index 97% rename from docs/guide/using-vue.md rename to docs/en/guide/using-vue.md index 3511ded0..70d18bce 100644 --- a/docs/guide/using-vue.md +++ b/docs/en/guide/using-vue.md @@ -224,7 +224,7 @@ Then you can use the following in Markdown and theme components: ## Using Teleports -Vitepress currently has SSG support for teleports to body only. For other targets, you can wrap them inside the built-in `` component or inject the teleport markup into the correct location in your final page HTML through [`postRender` hook](../reference/site-config#postrender). +VitePress currently has SSG support for teleports to body only. For other targets, you can wrap them inside the built-in `` component or inject the teleport markup into the correct location in your final page HTML through [`postRender` hook](../reference/site-config#postrender). @@ -243,8 +243,8 @@ Vitepress currently has SSG support for teleports to body only. For other target ``` +``` + +Resultado (**atención!**: colores destellantes, movimientos súbitos, luces brillantes): + +
+Demo + +![Demo de Transición de Alternancia de Apariencia](/appearance-toggle-transition.webp) + +
+ +Consulte [Chrome Docs](https://developer.chrome.com/docs/web-platform/view-transitions/) para mas detalles sobre _view transitions_. + +### En el Cambio de Ruta {#on-route-change} + +En breve. + +## Substituyendo Componentes Internos {#overriding-internal-components} + +Puede usar los [aliases](https://vitejs.dev/config/shared-options.html#resolve-alias) Vite para substituir los componentes del tema por defecto por los suyos personalizados: + +```ts +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vitepress' + +export default defineConfig({ + vite: { + resolve: { + alias: [ + { + find: /^.*\/VPNavBar\.vue$/, + replacement: fileURLToPath( + new URL('./components/CustomNavBar.vue', import.meta.url) + ) + } + ] + } + } +}) +``` + +Para saber el nombre exacto del componente consulte [nuestro código fuente](https://github.com/vuejs/vitepress/tree/main/src/client/theme-default/components). Como los componentes son internos, hay una pequeña chance de que el nombre sea actualizado entre lanzamientos secundarios. diff --git a/docs/es/guide/frontmatter.md b/docs/es/guide/frontmatter.md new file mode 100644 index 00000000..84736639 --- /dev/null +++ b/docs/es/guide/frontmatter.md @@ -0,0 +1,48 @@ +# Frontmatter + +## Uso {#usage} + +VitePress soporta frontmatter YAML en todos los archivos Markdown, procesandolos con [gray-matter](https://github.com/jonschlinkert/gray-matter). El frontmatter debe estar en la parte superior del archivo Markdown (antes de cualquier elemento, incluyendo tags ` + + +``` + +## Soporte a RTL (Experimental) {#rtl-support-experimental} + +Para soporte a RTL (Right to Left), especifique `dir: 'rtl'` en la configuración y use algún plugin RTLCSS PostCSS como , o . Necesitará configurar su plugin PostCSS para usar `:where([dir="ltr"])` y `:where([dir="rtl"])` como prefijos para evitar problemas de especificidad CSS. diff --git a/docs/es/guide/markdown.md b/docs/es/guide/markdown.md new file mode 100644 index 00000000..87cd9c35 --- /dev/null +++ b/docs/es/guide/markdown.md @@ -0,0 +1,930 @@ +# Extensiones Markdown {#markdown-extensions} + +VitePress viene con Extensiones embutidas. + +## Anchors de Header {#header-anchors} + +Los Header reciben la aplicación automáticamente de links anchor. La presentación de los anchor puede ser configurada usando la opción `markdown.anchor`. + +### Anchor personalizados {#custom-anchors} + +Para especificar un _tag_ anchor personalizado para um header en vex de usar la generada automáticamente, adicione un sufijo al header: + +``` +# Usando anchors personalizados {#mi-anchor} +``` + +Esto permite que tenga un link del header como `#mi-anchor` en vez del default `#usando-anchors-personalizados`. + +## Links {#links} + +Ambos links internos y externos reciben tratamiento especial. + +### Links Internos {#internal-links} + +Los links internos son convertidos en links de enrutador para navegación SPA. Además de eso , todo archivo `index.md` contenido en cada subdirectorio será automáticamente convertido en `index.html`, con la URL correspondiente `/`. + +Por ejemplo, dada la siguiente estructura de directorios: + +``` +. +├─ index.md +├─ foo +│ ├─ index.md +│ ├─ one.md +│ └─ two.md +└─ bar + ├─ index.md + ├─ three.md + └─ four.md +``` + +Y suponiendo que está en `foo/one.md`: + +```md +[Página Inicial](/) +[foo](/foo/) +[foo heading](./#heading) +[bar - three](../bar/three) +[bar - three](../bar/three.md) +[bar - four](../bar/four.html) +``` + +### Sufijo de Página {#page-suffix} + +Páginas y links internos son generados con el sufijo `.html` por defecto. + +### Links Externos {#external-links} + +Links externos reciben automáticamente `target="_blank" rel="noreferrer"`: + +- [vuejs.org](https://vuejs.org) +- [VitePress no GitHub](https://github.com/vuejs/vitepress) + +## Frontmatter {#frontmatter} + +[YAML frontmatter](https://jekyllrb.com/docs/front-matter/) es soportado por defecto: + +```yaml +--- +título: Escribiendo como un Hacker +idioma: es-CO +--- +``` + +Esos datos estarán disponibles para el resto de la página, junto con todos los componentes personalizados y de temas. + +Para más detalles, vea [Frontmatter](../reference/frontmatter-config). + +## Tablas al Estilo GitHub {#github-style-tables} + +**Entrada** + +```md +| Tablas | Son | Geniales| +| ------------- | :-----------: | ----: | +| col 3 está | à direita | $1600 | +| col 2 está | centralizada | $12 | +| listras | são legais | $1 | +``` + +**Salida** + +| Tablas | Son | Geniales | +| ------------- | :-----------: | -----: | +| col 3 está | à direita | \$1600 | +| col 2 está | centralizada | \$12 | +| listras | são legais | \$1 | + +## Emoji :tada: + +**Entrada** + +``` +:tada: :100: +``` + +**Salida** + +:tada: :100: + +Una [lista de todos los emojis](https://github.com/markdown-it/markdown-it-emoji/blob/master/lib/data/full.mjs) está disponible. + +## Tabla de Contenido (TOC) + +**Entrada** + +``` +[[toc]] +``` + +**Salida** + +[[toc]] + +La presentación de TOC (Table of Contents) puede ser configurada usando la opción `markdown.toc`. + +## Contenedores Personalizados {#custom-containers} + +Contenedores personalizados pueden ser definidos por sus tipos, títulos y contenidos. + +### Título por Defecto {#default-title} + +**Entrada** + +```md +::: info +Este es un bloque de información. +::: + +::: tip +Este es un aviso. +::: + +::: warning +Esto es una advertencia. +::: + +::: danger +Este es un aviso de peligro. +::: + +::: details +Este es un bloque de detalles. +::: +``` + +**Salida** + +::: info +Este es un bloque de información. +::: + +::: tip +Este es un aviso. +::: + +::: warning +Esto es una advertencia. +::: + +::: danger +Este es un aviso de peligro. +::: + +::: details +Este es un bloque de detalles. +::: + +### Título Personalizado {#custom-title} + +Puede definir un título personalizado adicionando el texto inmediatamente después del "tipo" del recipiente. + +**Entrada** + +```md +::: danger STOP +Zona de peligro, no siga +::: + +::: details Click para ver el código +```js +console.log('Hola, VitePress!') +``` +::: +``` +``` + +**Salida** + +::: danger STOP +Zona de peligro, no siga +::: + +::: details Click para ver el código +```js +console.log('Hola, VitePress!') +``` +::: + +Además de eso, puede definir títulos personalizados globalmente adicionando el siguiente contenifo en el archivo de configuración del sitio, útil si no estuviera escribiendo en ingles: + +```ts +// config.ts +export default defineConfig({ + // ... + markdown: { + container: { + tipLabel: '提示', + warningLabel: '警告', + dangerLabel: '危险', + infoLabel: '信息', + detailsLabel: '详细信息' + } + } + // ... +}) +``` + +### `raw` + +Este es un recipiente especial que puee ser usado para evitar conflictos de estilo y enrutador con VitePress. Esto es especialmente útil al documentar bibliotecas de componentes. Puede tambien verificar [whyframe](https://whyframe.dev/docs/integrations/vitepress) para mejor aislamiento. + +**Sintaxis** + +```md +::: raw +Envuelve en un
+::: +``` + +La clase `vp-raw` también puede ser usada directamente en elementos. El aislamiento de estilo es actualmente opcional: + +- Instale `postcss` con su gestor de paquetes preferido: + + ```sh + $ npm add -D postcss + ``` + +- Cree un archivo llamado `docs/postcss.config.mjs` y adicione lo siguiente: + + ```js + import { postcssIsolateStyles } from 'vitepress' + + export default { + plugins: [postcssIsolateStyles()] + } + ``` + + El utiliza [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) internamente. Puede pasar opciones así: + + ```js + postcssIsolateStyles({ + includeFiles: [/vp-doc\.css/] // o padrão é /base\.css/ + }) + ``` + +## Alertas en estilo GitHub {#github-flavored-alerts} + +VitePress también soporta [alertas en estilo GitHub](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts) para presentar como un bloque de llamada. Ellos serán presentados de la misma forma que [elementos personalizados](#custom-containers). + +```md +> [!NOTE] +> Destaca informaciones que los usuarios deben tener en consideración, incluso leyendo rapidamente. + +> [!TIP] +> Informaciones opcionales para ayudar al usuario a tener más éxito. + +> [!IMPORTANT] +> Informaciones cruciales necesarias par que los usuarios tengan éxito. + +> [!WARNING] +> Contenido critico exigiendo atención inmediata del usuario debido a riesgos potenciales. + +> [!CAUTION] +> Potenciales consecuencias negativas de una acción. +``` + +> [!NOTE] +> Destaca informaciones que los usuarios deben tener en consideración, incluso leyendo rapidamente. + +> [!TIP] +> Informaciones opcionales para ayudar al usuario a tener más éxito. + +> [!IMPORTANT] +> Informaciones cruciales necesarias par que los usuarios tengan éxito. + +> [!WARNING] +> Contenido critico exigiendo atención inmediata del usuario debido a riesgos potenciales. + +> [!CAUTION] +> Potenciales consecuencias negativas de una acción. + +## Destaque de Sintaxis en Bloques de Código {#syntax-highlighting-in-code-blocks} + +VitePress utiliza [Shiki](https://github.com/shikijs/shiki) para destacar la sintaxis del lenguaje en bloques de código Markdown, usando texto coloreado. Shiki soporta una amplia variedad de lenguajes de programación. Todo lo que necesita es adicionar un _alias_ de lenguaje válido después de los backticks iniciales del bloque de código: + +**Entrada** + +```` +```js +export default { + name: 'MyComponent', + // ... +} +``` +```` + +```` +```html +
    +
  • + {{ todo.text }} +
  • +
+``` +```` + +**Salida** + +```js +export default { + name: 'MyComponent' + // ... +} +``` + +```html +
    +
  • + {{ todo.text }} +
  • +
+``` + +Una [lista de lenguajes válidas](https://shiki.style/languages) está disponible en el repositório Shiki. + +También puede personalizar el tema de destaque de sintaxis en la configuración de la aplicación. Consulte las [opciones `markdown`](../reference/site-config#markdown) para más detalles. + +## Destaque de Linea en Bloques de Código {#line-highlighting-in-code-blocks} + +**Entrada** + +```` +```js{4} +export default { + data () { + return { + msg: 'Destacado!' + } + } +} +``` +```` + +**Salida** + +```js{4} +export default { + data () { + return { + msg: 'Destacado!' + } + } +} +``` + +Además de una única linea, puede también especificar múltiples lineas únicas, intervalos, o ambos: + +- Intervalos de linea: por ejemplo, `{5-8}`, `{3-10}`, `{10-17}` +- Múltiples lineas únicas: por ejemplo, `{4,7,9}` +- Intervalos de linea y lineas únicas: por ejemplo, `{4,7-13,16,23-27,40}` + +**Entrada** + +```` +```js{1,4,6-8} +export default { // Destacado + data () { + return { + msg: `Destacado! + Esta linea no está destacada, + pero esta y las próximas están.`, + motd: 'VitePress es increible', + lorem: 'ipsum' + } + } +} +``` +```` + +**Salida** + +```js{1,4,6-8} +export default { // Destacado + data () { + return { + msg: `Destacado! + Esta linea no está destacada, + pero esta y las próximas están.`, + motd: 'VitePress es increible', + lorem: 'ipsum', + } + } +} +``` + +Alternativamente, es posible destacar directamente en la linea usando el comentario `// [!code highlight]`. + +**Entrada** + +```` +```js +export default { + data () { + return { + msg: 'Destacado!' // [!!code highlight] + } + } +} +``` +```` + +**Saída** + +```js +export default { + data() { + return { + msg: 'Destacado!' // [!code highlight] + } + } +} +``` + +## Enfoque en Bloques de Código {#focus-in-code-blocks} + +Adicionando el comentario `// [!code focus]` en una linea, esta será destacada y desenfocará las otras partes del código. + +Además, puede definir el número de lineas para enfocar usando `// [!code focus:]`. + +**Entrada** + +```` +```js +export default { + data () { + return { + msg: 'Enfocado!' // [!!code focus] + } + } +} +``` +```` + +**Salida** + +```js +export default { + data() { + return { + msg: 'Enfocado!' // [!code focus] + } + } +} +``` + +## Diferencias Coloreadas en Bloques de Código {#colored-diffs-in-code-blocks} + +Adicionar los comentarios `// [!code --]` o `// [!code ++]` en una linea creará una diferencia en esa linea, manteniendo los colores del bloque de código. + +**Entrada** + +```` +```js +export default { + data () { + return { + msg: 'Borrado' // [!!code --] + msg: 'Adicionado' // [!!code ++] + } + } +} +``` +```` + +**Salida** + +```js +export default { + data () { + return { + msg: 'Borrado' // [!code --] + msg: 'Adicionado' // [!code ++] + } + } +} +``` + +## Errores y Avisos en Bloques de Código {#errors-and-warnings-in-code-blocks} + +Adicionar los comentarios `// [!code warning]` o `// [!code error]` en una linea coloreará los bloques conforme necesário. + +**Entrada** + +```` +```js +export default { + data () { + return { + msg: 'Error', // [!!code error] + msg: 'Aviso' // [!!code warning] + } + } +} +``` +```` + +**Salida** + +```js +export default { + data() { + return { + msg: 'Error', // [!code error] + msg: 'Aviso' // [!code warning] + } + } +} +``` + +## Números de Linea {#line-numbers} + +Puede habilitar números de linea para cada bloque de código a través del archivo de configuración: + +```js +export default { + markdown: { + lineNumbers: true + } +} +``` + +Consulte las [opciones markdown](../reference/site-config#markdown) para más detalles. + +Puede adicionar la marca `:line-numbers` / `:no-line-numbers` en sus bloques de código para substituir el valor definido en la configuración. + +También puede personalizar el número inicial de linea adicionando `=` después `:line-numbers`. Por ejemplo, `:line-numbers=2` significa que los números de las lineas en los bloques de código comenzarán a partir de `2`. + +**Entrada** + +````md +```ts {1} +// números de linea desactivados por defecto +const line2 = 'Esta es la linea 2' +const line3 = 'Esta es la linea 3' +``` + +```ts:line-numbers {1} +// números de linea activados +const line2 = 'Esta es la linea 2' +const line3 = 'Esta es la linea 3' +``` + +```ts:line-numbers=2 {1} +// números de linea activados y comienzan en 2 +const line3 = 'Esta es la linea 3' +const line4 = 'Esta es la linea 4' +``` +```` + +**Salida** + +```ts {1} +// números de linea desactivados por defecto +const line2 = 'Esta es la linea 2' +const line3 = 'Esta es la linea 3' +``` + +```ts:line-numbers {1} +// números de linea activados +const line2 = 'Esta es la linea 2' +const line3 = 'Esta es la linea 3' +``` + +```ts:line-numbers=2 {1} +// números de linea activados y comienzan en 2 +const line3 = 'Esta es la linea 3' +const line4 = 'Esta es la linea 4' +``` + +## Importar _Snippets_ de Código {#import-code-snippets} + +Puede importar pedazos de código de archivos existentes usando la siguiente sintaxis: + +```md +<<< @/filepath +``` + +También soporta [destaque de linea](#line-highlighting-in-code-blocks): + +```md +<<< @/filepath{highlightLines} +``` + +**Entrada** + +```md +<<< @/snippets/snippet.js{2} +``` + +**Archivo de Código** + +<<< @/snippets/snippet.js + +**Salida** + +<<< @/snippets/snippet.js{2} + +::: tip + +El valor de `@` corresponde a la raiz del código fuente. Por defecto, es la raiz del proyecto VitePress, a menos que `srcDir` sea configurado. Alternativamente, puede también importar de paths relativos: + +```md +<<< ../snippets/snippet.js +``` + +::: + +También puede usar una [región VS Code](https://code.visualstudio.com/docs/editor/codebasics#_folding) para incluir apenas la parte correspondiente del archivo de código. Puede proporcionar un nombre de región personalizado después de `#` siguiendo el path del archivo: + +**Entrada** + +```md +<<< @/snippets/snippet-with-region.js#snippet{1} +``` + +**Archivo de Código** + +<<< @/snippets/snippet-with-region.js + +**Salida** + +<<< @/snippets/snippet-with-region.js#snippet{1} + +También puede especificar el idioma dentro de llaves (`{}`), así: + +```md +<<< @/snippets/snippet.cs{c#} + + + +<<< @/snippets/snippet.cs{1,2,4-6 c#} + + + +<<< @/snippets/snippet.cs{1,2,4-6 c#:line-numbers} +``` + +Esto es útil si el lenguaje original no puede ser inferida por la extensión de archivo. + +## Grupos de Código {#code-groups} + +Puede agrupar varios bloques de código así: + +**Entrada** + +````md +::: code-group + +```js [config.js] +/** + * @type {import('vitepress').UserConfig} + */ +const config = { + // ... +} + +export default config +``` + +```ts [config.ts] +import type { UserConfig } from 'vitepress' + +const config: UserConfig = { + // ... +} + +export default config +``` + +::: +```` + +**Salída** + +::: code-group + +```js [config.js] +/** + * @type {import('vitepress').UserConfig} + */ +const config = { + // ... +} + +export default config +``` + +```ts [config.ts] +import type { UserConfig } from 'vitepress' + +const config: UserConfig = { + // ... +} + +export default config +``` + +::: + +También puede [importar _snippets_ de código](#import-code-snippets) en grupos de código: + +**Entrada** + +```md +::: code-group + + + +<<< @/snippets/snippet.js + + + +<<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [snippet with region] + +::: +``` + +**Output** + +::: code-group + +<<< @/snippets/snippet.js + +<<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [snippet with region] + +::: + +## Inclusión de Archivo Markdown {#markdown-file-inclusion} + +Puede incluir un archivo markdown en otro archvo markdown, incluso anidado. + +::: tip +Puede prefijar el path del markdown con `@`, el actuará como la raiz de origen. Por defecto, es la raiz del projecto VitePress, a menos que `srcDir` sea configurado. +::: + +Por ejemplo, puede incluir un archivo markdown relativo usando esto: + +**Entrada** + +```md +# Documentación + +## Conceptos Básicos + + +``` + +**Archivo de Parte** (`parts/basics.md`) + +```md +Algunas cosas básicas. + +### Configuración + +Puede ser creada usando `.foorc.json`. +``` + +**Código Equivalente** + +```md +# Documentación + +## Conceptos básicos + +Algunas cosas básicas + +### Configuración + +Puede ser creada usando `.foorc.json`. +``` + +También soporta la selección de un intervalo de lineas: + +**Entrada** + +```md +# Documentación + +## Conceptos Básicos + + +``` + +**Archivo de Parte** (`parts/basics.md`) + +```md +Algunas cosas básicas. + +### Configuración + +Puede ser creada usando `.foorc.json`. +``` + +**Código Equivalente** + +```md +# Documentación + +## Conceptos Básicos + +### Configuración + +Puede ser creada usando `.foorc.json`. +``` + +El formato del intervalo de lineas seleccionado puede ser: `{3,}`, `{,10}`, `{1,10}` + +::: warning +Observe que esto no genera errores si el archivo no está presente. Por lo tanto, al usar este recurso, asegurese de que el contenido está siendo mostrado como se espera.::: + +## Ecuaciones Matemáticas {#math-equations} + +Esto es actualmente opcional. Para activarlo, necesita instalar `markdown-it-mathjax3` y definir `markdown.math` como `true` en su archivo de configuración: + +```sh +npm add -D markdown-it-mathjax3 +``` + +```ts +// .vitepress/config.ts +export default { + markdown: { + math: true + } +} +``` + +**Entrada** + +```md +Cuando $a \ne 0$, existen dos soluciones para $(ax^2 + bx + c = 0)$ y ellas son +$$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ + +**Ecuaciones de Maxwell:** + +| ecuación | descripción | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| $\nabla \cdot \vec{\mathbf{B}} = 0$ | la divergencia de $\vec{\mathbf{B}}$ es cero | +| $\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | la rotacional de $\vec{\mathbf{E}}$ es proporcional a la tasa de variación de $\vec{\mathbf{B}}$ | +| $\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _hã?_ | + +**Salída** + +Cuando $a \ne 0$, existen dos soluciones para $(ax^2 + bx + c = 0)$ y ellas son +$$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ + +**Ecuaciones de Maxwell:** + +| ecuación | descripción | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| $\nabla \cdot \vec{\mathbf{B}} = 0$ | la divergencia de $\vec{\mathbf{B}}$ es cero | +| $\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | la rotacional de $\vec{\mathbf{E}}$ es proporcional a la tasa de variación de $\vec{\mathbf{B}}$ | +| $\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _hã?_ | + +## _Lazy Loading_ de Imagenes {#image-lazy-loading} + +Puede activar la "carga perezosa" para cada imagen adicionada via markdown definiendo `lazyLoading` como `true` en su archivo de configuración: + +```js +export default { + markdown: { + image: { + // la carga perezosa de imagenes está desactivada por defecto + lazyLoading: true + } + } +} +``` + +## Configuración Avanzada {#advanced-configuration} + +VitePress usa [markdown-it](https://github.com/markdown-it/markdown-it) como interprete Markdown. Muchas de las extensiones arriba son implementadas por medio de _plugins_ personalizados. Puede personalizar más la instancia `markdown-it` usando la opción `markdown` en `.vitepress/config.js`: + +```js +import { defineConfig } from 'vitepress' +import markdownItAnchor from 'markdown-it-anchor' +import markdownItFoo from 'markdown-it-foo' + +export default defineConfig({ + markdown: { + // opciones para markdown-it-anchor + // https://github.com/valeriangalliat/markdown-it-anchor#usage + anchor: { + permalink: markdownItAnchor.permalink.headerLink() + }, + + // opciones para @mdit-vue/plugin-toc + // https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc#options + toc: { level: [1, 2] }, + + config: (md) => { + // use más plugins markdown-it! + md.use(markdownItFoo) + } + } +}) +``` + +Consulte la lista completa de propiedades configurables en [Referencia de Configuración: Configuración de la Aplicación](../reference/site-config#markdown). diff --git a/docs/es/guide/mpa-mode.md b/docs/es/guide/mpa-mode.md new file mode 100644 index 00000000..1e8a7d26 --- /dev/null +++ b/docs/es/guide/mpa-mode.md @@ -0,0 +1,23 @@ +# Modo MPA {#mpa-mode} + +El modo MPA (Aplicación de multiples páginas) puede ser habilitado por la linea de comandos con `vitepress build --mpa`, o a través de la configuración por la opción `mpa: true`. + +En el modo MPA, todas las páginas son presentadas por defecto sin JavaScript incluído. Como resultado, el sitio en producción probablemente tendrá una marca de desempeño de visita inicial superior con herramientas de auditoría. + +Sin embargo, debido a la ausencia de navegación SPA, los links entre páginas resultan en recargas de página completos. Navegaciones después de la carga en el modo MPA no parecerán tan instantáneos en comparación con el modo SPA. + +También note que no tener JavaScript por defecto significa que está esencialmente utilizando Vue como modelo de lenguaje en el lado del servidor. Nungun manipulador de eventos será embutido en el navegador, entonces no habrá interactividad. Para cargar JavaScript en el lado del cliente, necesitará usar el tag especial ` + +# Hola +``` + +` +``` + +### Presentando Contenido Crudo {#rendering-raw-content} + +Parámetros pasados para una página serán serializados en la carga JavaScript del cliente, por lo tanto, evite pasar datos pesados en los parámetros, como Markdown crudo o contenido HTML obtenido de un CSS remoto. + +En lugar de eso, puede pasar tal contenido para cada página usando la propiedad `content` en cada objeto de path: + +```js +export default { + async paths() { + const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + + return posts.map((post) => { + return { + params: { id: post.id }, + content: post.content // Markdown o HTML crudo + } + }) + } +} +``` + +En seguida, use la siguiente sintaxis especial para presentar el contenido como parte del propio archivo Markdown: + +```md + +``` diff --git a/docs/es/guide/sitemap-generation.md b/docs/es/guide/sitemap-generation.md new file mode 100644 index 00000000..09f10aea --- /dev/null +++ b/docs/es/guide/sitemap-generation.md @@ -0,0 +1,53 @@ +# Generación de Sitemap {#sitemap-generation} + +VitePress viene con soporte embutido para generar un archivo `sitemap.xml` para su sitio. Para habilitar, adicione lo siguiente a su `.vitepress/config.js`: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + sitemap: { + hostname: 'https://example.com' + } +}) +``` + +Para tener tags `` en su `sitemap.xml`, puede habilitar la opción [`lastUpdated`](../reference/default-theme-last-updated). + +## Opciones {#options} + +El soporte de Sitemap es alimentado por el módulo [`sitemap`](https://www.npmjs.com/package/sitemap). Puede pasar cualquiera de las opciones soportadas por el en la opción `sitemap` de su archivo de configuración. Estos serán pasados directamente al constructor `SitemapStream`. Consulte la [documentación `sitemap`](https://www.npmjs.com/package/sitemap#options-you-can-pass) para más detalles. Ejemplo: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + sitemap: { + hostname: 'https://example.com', + lastmodDateOnly: false + } +}) +``` + +## Hook `transformItems` + +Puede usar el hook `sitemap.transformItems` para modificar los items del sitemap antes de ser escritos en el archivo `sitemap.xml`. Este hook es llamado como un _array_ de items sitemap y espera un _array_ de items sitemap como retorno. Ejemplo: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + sitemap: { + hostname: 'https://example.com', + transformItems: (items) => { + // adiciona nuevos items o modifica/filtra items existentes + items.push({ + url: '/extra-page', + changefreq: 'monthly', + priority: 0.8 + }) + return items + } + } +}) +``` diff --git a/docs/es/guide/ssr-compat.md b/docs/es/guide/ssr-compat.md new file mode 100644 index 00000000..af0d26d9 --- /dev/null +++ b/docs/es/guide/ssr-compat.md @@ -0,0 +1,137 @@ +--- +outline: deep +--- + +# 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. + +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. + +## `` + +Se está usando o demostrando componentes que no son compatibles con SSR (por ejemplo, contienen directivas personalizadas), puede envolverlos en el componente embutido ``: + +```md + + + +``` + +## 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. + +### Importando en el Hook `mounted` {#importing-in-mounted-hook} + +```vue + +``` + +### 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)): + +```js +if (!import.meta.env.SSR) { + import('./lib-que-accede-window-en-la-importacion').then((module) => { + // 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: + +```js +// .vitepress/theme/index.js +/** @type {import('vitepress').Theme} */ +export default { + // ... + async enhanceApp({ app }) { + if (!import.meta.env.SSR) { + const plugin = await import('plugin-que-accede-window-en-la-importacion') + app.use(plugin.default) + } + } +} +``` + +Si está usando TypeScript: +```ts +// .vitepress/theme/index.ts +import type { Theme } from 'vitepress' + +export default { + // ... + async enhanceApp({ app }) { + if (!import.meta.env.SSR) { + const plugin = await import('plugin-que-accede-window-en-la-importacion') + app.use(plugin.default) + } + } +} satisfies Theme +``` + +### `defineClientComponent` + +VitePress proporciona un auxiliar de conveniencia para importar componentes Vue que acceden APIs del navegador en la importación. + +```vue + + + +``` + +Puede también pasar propiedades/hijos/_slots_ para el componente objetivo: + +```vue + + + +``` + +El componente objetivo solo será importado en el hook `mounted` del componente que lo envuelve. diff --git a/docs/es/guide/using-vue.md b/docs/es/guide/using-vue.md new file mode 100644 index 00000000..97cfbf93 --- /dev/null +++ b/docs/es/guide/using-vue.md @@ -0,0 +1,256 @@ +# Usando Vue en Markdown {#using-vue-in-markdown} + +En VitePress, cada archivo Markdown es compilado para HTML y entonces procesado como un [Componente de Archivo Único de Vue](https://vuejs.org/guide/scaling-up/sfc.html). Esto significa que puede usar cualquier funcionalidad de Vue dentro del Markdown, incluyendo la interpolación dinámica, usar componentes Vue o lógica arbitrária de componentes Vue dentro de la página adicionando una tag ` + +## Contenido Markdown + +El conteo es: {{ count }} + + + + +``` + +::: warning Evite ` +``` + +## Usando _Teleports_ {#using-teleports} + +VitePress actualmente ofrece soporte a SSG para _teleports_ apenas para el cuerpo. Para otros objetivos, puede envolverlos dentro del componente embutido `` o inyectar la marcación de _teleport_ en la localización correcta en su página final HTML por medio del [hook `postRender`](../reference/site-config#postrender). + + + +::: details +<<< @/components/ModalDemo.vue +::: + +```md + + +
+ // ... +
+
+
+``` + + + + diff --git a/docs/es/guide/what-is-vitepress.md b/docs/es/guide/what-is-vitepress.md new file mode 100644 index 00000000..1d7558f0 --- /dev/null +++ b/docs/es/guide/what-is-vitepress.md @@ -0,0 +1,56 @@ +# Qué es VitePress? {#what-is-vitepress} + +VitePress es un [Generador de Sitios Estáticos](https://en.wikipedia.org/wiki/Static_site_generator) (SSG) proyectado para crear sitios rápidos y centrados en contenido. En suma, VitePress utiliza su contenido fuente escrito en [Markdown](https://en.wikipedia.org/wiki/Markdown), aplica un tema a el y genera páginas HTML estáticas que pueden ser facilmente implantadas en cualquier lugar. + +
+Quiere apenas experimentar? Valla al [Início Rápido](./getting-started). + +
+ +## Casos de Uso {#use-cases} + +- **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). + + La [documentación oficial Vue.js](https://vuejs.org/) también está basada en VitePress, pero usa un tema personalizado compartido entre varias traducciones. + +- **Blogs, Portfólios y sitios de Marketing** + + VitePress soporta [temas totalmente personalizables](./custom-theme), con la experiencia de desarrollador por defecto de una aplicaciónn Vite + Vue. La construcción con Vite significa que puede aprovechar directamente plugins Vite de su rico ecosistema. Adicionalmente, VitePress proporciona APIs flexibles para[cargar datos](./data-loading) (locales o remotos) y [generar rutas dinámicamente](./routing#dynamic-routes). Puede usarlo para construir practicamente cualquier cosa desde que los datos puedan ser determinados en el momento del build. + + El [blog oficial Vue.js](https://blog.vuejs.org/) es un blog simple que genera su página inicial basada en contenido local. + +## Experiencia de Desarrollador {#developer-experience} + +VitePress visa proporcionar excelente Experiencia de Desarrollador (DX) al trabajar con contenido en Markdown. + +- **[Alimentado por Vite:](https://vitejs.dev/)** inicialización instantánea del servidor, con ediciones siempre reflejadas instantáneamente (<100ms) sin recarga de página. + +- **[Extensiones Markdown Integradas:](./markdown)** Frontmatter, tablas, destaque de sintaxis... usted escoje. Especificamente, VitePress proporciona muchos recursos para trabajar con bloques de código, tornandolo ideal para documentación altamente técnica. + +- **[Markdown Mejorado por Vue:](./using-vue)** cada página Markdown es también un [Componente de Archivo único](https://pt.vuejs.org/guide/scaling-up/sfc.html), gracias a la compatibilidad de sintaxis de 100% del template Vue con HTML. Puede también incorporar iteractividad con su contenido estático usando recursos de template Vue o componentes Vue importados. + +## Desempeño {#performance} + +Al contrario de muchos SSGs tradicionales, un sitio generado por VitePress es la verdad una [Single Page Application](https://en.wikipedia.org/wiki/Single-page_application) (SPA). + +- **Carga Inicial Rápida** + + La visita inicial a cualquier página será servida con el HTML estático pré-renderizado para velocidad de carga rápida y SEO optimizado. La página entonces carga un paquete JavaScript que transforma la página en una SPA Vue ("hidratación"). El proceso de hidratación es extremadamente rápido: en [PageSpeed Insights](https://pagespeed.web.dev/report?url=https%3A%2F%2Fvitepress.dev%2F), sitios típicos VitePress alcanzan puntuaciones de desempeño casi perfectas, incluso en dispositivos móbiles de bajo desempeño con una red lenta. + +- **Navegación Rápida pos-carga** + + Más importante todavía, el modelo SPA lleva a una mejor experiencia del usuario **después** de la carga inicial. La navegación subsequente dentro del sitio no causará una recarga adicional completa de la página. En vez de eso, el contenido de la página de entrada será buscado y actualizado dinámicamente. VitePress también pre-carga automáticamente pedazos de página para links que están dentro del viewport. En la mayoría de los casos, la navegación pos-carga parecerá instantánea. + +- **Interactividad Sin Penalidades** + + Para ser capaz de hidratar las partes dinámicas Vue incorporadas dentro del Markdown estático, cada página Markdown es procesada como un componente Vue y compilada en JavaScript. Esto puede parecer ineficiente, pero el compilador Vue es suficientemente inteligente para separar las partes estáticas y dinámicas, minimizando tanto el costo de hidratación así como el tamaño de carga. Para la carga inicial de la página, las partes estáticas son automáticamente eliminadas de la carga JavaScript y omitidas durante la hidratación. + +## Y VuePress? {#what-about-vuepress} + +VitePress es el sucesor espiritual de VuePress. VuePress era orginalmente basado en Vue 2 y webpack. Con Vue 3 y Vite, VitePress ofrece una experiencia de desarrollador significamente mejor, mejor desempeño en producción, un tema por defecto más pulido y un API de personalización más flexible. + +A diferencia del API entre VitePress y VuePress reside principalmente en temas y personalización. Si estuviera usando VuePress 1 con el tema por defecto, la migración para VitePress debe ser relativamente simple. + +También hubo esfuerzo invertido en VuePress 2, que también soporta Vue 3 y Vite con mejor compatibilidad que con VuePress 1. Sin embargo, mantener dos SSGs en paralelo no es sustentable, entonces el equipo Vue decidió enfocarse en VitePress como el principal SSG recomendado a largo plazo. diff --git a/docs/es/index.md b/docs/es/index.md new file mode 100644 index 00000000..bf9701e5 --- /dev/null +++ b/docs/es/index.md @@ -0,0 +1,60 @@ +--- +layout: home + +title: VitePress +titleTemplate: Generador de Sitios Estáticos desarrollado con Vite y Vue + +hero: + name: VitePress + text: Generador de Sitios Estáticos Vite y Vue + tagline: Markdown para obtener lindos documentos en minutos + actions: + - theme: brand + text: Qué es VitePress? + link: /es/guide/what-is-vitepress + - theme: alt + text: Iniciar + link: /es/guide/getting-started + - theme: alt + text: GitHub + link: https://github.com/vuejs/vitepress + image: + src: /vitepress-logo-large.webp + alt: VitePress + +features: + - icon: 📝 + title: Concéntrese en su contenido + details: Cree lindos sitios de documentación apenas con markdown. + - icon: + title: Disfruta de la experiencia Vite + details: Inicio instantaneo de servidor, actualizaciones ultrarrápidas, y plugins del ecosistema Vite. + - icon: + title: Personaliza con Vue + details: Usa la sintaxis y componentes Vue directamente en markdown, o construye temas personalizados con Vue. + - icon: 🚀 + title: Entrega rápida de sitios + details: Carga inicial rápida con HTML estático, navegación rápida con enrutamiento del lado del cliente. +--- + + diff --git a/docs/es/reference/cli.md b/docs/es/reference/cli.md new file mode 100644 index 00000000..f5a5583c --- /dev/null +++ b/docs/es/reference/cli.md @@ -0,0 +1,74 @@ +# Intefaz de Linea de Comando {#command-line-interface} + +## `vitepress dev` + + Inicia el servidor de desarrollo VitePress con el directorio designado como raíz. Por defecto, utiliza el director actual. el comando `dev` también se puede omitir cuando se ejecuta el directorio actual. + +### Uso + +```sh +# Comienza en el directorio actual, omite el `dev` +vitepress + +# iniciar en un subdirectorio +vitepress dev [root] +``` + +### Opciones {#options} + +| Opciones | Descripción | +| --------------- | ----------------------------------------------------------------- | +| `--open [path]` | Abre el navegador en el inicio (`boolean \| string`) | +| `--port ` | Especifica el puerto (`number`) | +| `--base ` | Ruta de base pública (por defecto: `/`) (`string`) | +| `--cors` | Habilitar CORS | +| `--strictPort` | Salir si el puerto especificado ya esta en uso (`boolean`) | +| `--force` | Obligar al optimizador a ignorar el cache y volver a empaquetar (`boolean`) | + +## `vitepress build` + +Compilar el sitio web de VitePress para producción. + +### Uso + +```sh +vitepress build [root] +``` + +### Opciones + +| Opción | Descripción | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | +| `--mpa` (experimental) | Compilar en [Modo MPA](../guide/mpa-mode) Sin hidratación del lado del cliente (`boolean`) | +| `--base ` | Ruta de base pública (por defecto: `/`) (`string`) | +| `--target ` | Transpilar objetivo (por defecto: `"modules"`) (`string`) | +| `--outDir ` | Directorio de salida relativo a **cwd** (por defecto: `/.vitepress/dist`) (`string`) | +| `--minify [minifier]` | Habilitar/desabilitar la minificación, o especifica un minero para usar (por defecto: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | +| `--assetsInlineLimit ` | Limitar los bytes para alinear los activos en base 64 (por defecto: `4096`) (`number`) | + +## `vitepress preview` + +Proporciona localmente la compilación de la producción. + +### Uso + +```sh +vitepress preview [root] +``` + +### Opciones + +| Opción | Descripción | +| --------------- | ------------------------------------------ | +| `--base ` | Ruta de base pública (por defecto: `/`) (`string`) | +| `--port ` | Especifica el puerto (`number`) | + +## `vitepress init` + +Inicia el [Asistente de Instalación](../guide/getting-started#setup-wizard) en el directorio actual. + +### Uso + +```sh +vitepress init +``` diff --git a/docs/es/reference/default-theme-badge.md b/docs/es/reference/default-theme-badge.md new file mode 100644 index 00000000..4c5e57eb --- /dev/null +++ b/docs/es/reference/default-theme-badge.md @@ -0,0 +1,69 @@ +# Badge {#badge} + +Los Badge te permite agregar estados a tus encabezados. Por ejemplo, podría resultar útil especificar el tipo de sección o la version compatible. + +## Uso {#usage} + +Puedes usar el componente `Badge` que está disponible globalmente. + +```html +### Title +### Title +### Title +### Title +``` + +el código anterior se representa como: + +### Title +### Title +### Title +### Title + +## Personalizar hijos {#custom-children} + +`` acepta `children` (hijos), que se mostrará en el badge. + +```html +### Title custom element +``` + +### Title custom element + +## Personalizar Tipo de Color {#customize-type-color} + +Puedes personalizar el estilo del badge anulando las variables CSS. los siguiente son los valores predeterminados: + +```css +:root { + --vp-badge-info-border: transparent; + --vp-badge-info-text: var(--vp-c-text-2); + --vp-badge-info-bg: var(--vp-c-default-soft); + + --vp-badge-tip-border: transparent; + --vp-badge-tip-text: var(--vp-c-brand-1); + --vp-badge-tip-bg: var(--vp-c-brand-soft); + + --vp-badge-warning-border: transparent; + --vp-badge-warning-text: var(--vp-c-warning-1); + --vp-badge-warning-bg: var(--vp-c-warning-soft); + + --vp-badge-danger-border: transparent; + --vp-badge-danger-text: var(--vp-c-danger-1); + --vp-badge-danger-bg: var(--vp-c-danger-soft); +} +``` + +## `` + +El componente `` acepta las siguiente propiedades: + +```ts +interface Props { + // Cuando se pasa `` ese valor es ignorado. + text?: string + + // El valor predeterminado es `tip`. + type?: 'info' | 'tip' | 'warning' | 'danger' +} +``` diff --git a/docs/es/reference/default-theme-carbon-ads.md b/docs/es/reference/default-theme-carbon-ads.md new file mode 100644 index 00000000..4ca016c5 --- /dev/null +++ b/docs/es/reference/default-theme-carbon-ads.md @@ -0,0 +1,22 @@ +# Carbon Ads {#carbon-ads} + +VitePress ha incorporado soporte nativo para [Carbon Ads](https://www.carbonads.net/). Al definir las credenciales de Carbon Ads en la configuración, VitePress mostrará anuncios en la página. + +```js +export default { + themeConfig: { + carbonAds: { + code: 'tu-código-carbon', + placement: 'tu-vinculación-carbon' + } + } +} +``` + +Estos valores se utilizan para llamar al script en CDN de carbon como se muestra a continuación. + +```js +`//cdn.carbonads.com/carbon.js?serve=${code}&placement=${placement}` +``` + +Para obtener más información de la configuración de Carbono Ads, por favor visite [Site Carbon Ads](https://www.carbonads.net/). diff --git a/docs/es/reference/default-theme-config.md b/docs/es/reference/default-theme-config.md new file mode 100644 index 00000000..72cebed7 --- /dev/null +++ b/docs/es/reference/default-theme-config.md @@ -0,0 +1,452 @@ +# Configuración del Tema Predeterminado {#default-theme-config} + +La configuración del tema te permite personalizar tu tema. puedes definir la configuración del tema a través de la opción `themeConfig` en el archivo de configuración: + +```ts +export default { + lang: 'pt-BR', + title: 'VitePress', + description: 'Generador de site estático Vite & Vue.', + + // Configuraciones relacionadas con el tema. + themeConfig: { + logo: '/logo.svg', + nav: [...], + sidebar: { ... } + } +} +``` + +**Las opciones documentadas de esta página se aplican unicamente al tema por defecto.** Diferentes temas esperan configuraciones diferentes de tema. Cuando se utiliza un tema personalizado, el objeto de configuración del tema se pasará al tema para que se puedan definir comportamientos condicionales. + +## i18nRouting + +- Tipo: `boolean` + +Cambie la configuración a, por ejemplo, `zh` será alterado para URL `/foo` (ou `/en/foo/`) para `/zh/foo`. Puedes desactivar este comportamiento configurado `themeConfig.i18nRouting` como `false`. + +## logo + +- Tipo: `ThemeableImage` + +Archivo de logotipo que se mostrará en la barra de navegación, justo antes del título del sitio. Acepta una ruta de cadena o un objeto para definir un logotipo diferente para los modos claro/oscuro. + +```ts +export default { + themeConfig: { + logo: '/logo.svg' + } +} +``` + +```ts +type ThemeableImage = + | string + | { src: string; alt?: string } + | { light: string; dark: string; alt?: string } +``` + +## siteTitle + +- Tipo: `string | false` + +Puedes personalizar este elemento para reemplazar el título del sitio predeterminado (`title` en configuración de la aplicación) en navegación. Cuando se establece como `false`, el título en la navegación quedará deshabilitado. Útil cuando tienes un `logo` que ya contiene el título del sitio. + +```ts +export default { + themeConfig: { + siteTitle: 'Hola mundo' + } +} +``` + +## nav + +- Tipo: `NavItem` + +La configuración del elemento del menú de navegación. Más detalles en [Tema Predeterminado: Navegación](./default-theme-nav#navigation-links). + +```ts +export default { + themeConfig: { + nav: [ + { text: 'Guia', link: '/guide' }, + { + text: 'Menú Dropdown', + items: [ + { text: 'Item A', link: '/item-1' }, + { text: 'Item B', link: '/item-2' }, + { text: 'Item C', link: '/item-3' } + ] + } + ] + } +} +``` + +```ts +type NavItem = NavItemWithLink | NavItemWithChildren + +interface NavItemWithLink { + text: string + link: string + activeMatch?: string + target?: string + rel?: string + noIcon?: boolean +} + +interface NavItemChildren { + text?: string + items: NavItemWithLink[] +} + +interface NavItemWithChildren { + text?: string + items: (NavItemChildren | NavItemWithLink)[] + activeMatch?: string +} +``` + +## sidebar + +- Tipo: `Sidebar` + +La configuración del elemento del menú de la barra lateral. Más detalles en [Tema Predeterminado: Barra Lateral](./default-theme-sidebar). + +```ts +export default { + themeConfig: { + sidebar: [ + { + text: 'Guia', + items: [ + { text: 'Introducción', link: '/introduction' }, + { text: 'A partir de', link: '/getting-started' }, + ... + ] + } + ] + } +} +``` + +```ts +export type Sidebar = SidebarItem[] | SidebarMulti + +export interface SidebarMulti { + [path: string]: SidebarItem[] +} + +export type SidebarItem = { + /** + * El rotulo del item. + */ + text?: string + + /** + * El link del item. + */ + link?: string + + /** + * Los hijos del item. + */ + items?: SidebarItem[] + + /** + * Si no se especifica, el grupo no es retráctil. + * + * Si es 'true', el grupo se puede contraer y está contraído de forma predeterminada. + * + * Si es 'false', el grupo se puede contraer pero se expande de forma predeterminada. + */ + collapsed?: boolean +} +``` + +## aside + +- Tipo: `boolean | 'left'` +- Estandar: `true` +- Puede ser anulado por la página a través de [frontmatter](./frontmatter-config#aside) + +Definir este valor como `false` evita que se muestre el elemento lateral.\ +Definir este valor como `true` presenta el lado de la derecha.\ +Definir este valor como `left` presenta el lado de la izquierda. + +Si desea deshabilitarlo para todas las vistas, debe usar `outline: false` en vez de eso. + +## outline + +- Tipo: `Outline | Outline['level'] | false` +- El nivel se puede superponer por página mediante [frontmatter](./frontmatter-config#outline) + +Definir este valor como `false` evita que el elemento se muestre _outline_. Consulte la interfaz para más detalles: + +```ts +interface Outline { + /** + * Los niveles de título que se mostrarán en el esquema. + * Un solo número significa que solo se mostrarán los títulos de ese nivel. + * Si se pasa una tupla, el primer número es el nivel mínimo y el segundo número es el nivel máximo. + * `'deep'` es lo mismo que `[2, 6]`, lo que significa que todos los titulos `

` a `

` serán mostrados. + * + * @default 2 + */ + level?: number | [number, number] | 'deep' + + /** + * El titulo que se mostrará en el equema. + * + * @default 'On this page' + */ + label?: string +} +``` + +## socialLinks + +- Tipo: `SocialLink[]` + +Puedes configurar esta opción para mostrar enlaces de redes sociales con íconos en la navegación. + +```ts +export default { + themeConfig: { + socialLinks: [ + { icon: 'github', link: 'https://github.com/vuejs/vitepress' }, + { icon: 'twitter', link: '...' }, + // También puedes agregar íconos personalizados pasando SVG como string: + { + icon: { + svg: 'Dribbble' + }, + link: '...', + // También puedes incluir una etiqueta personalizada de accesibilidad (opcional pero recomendada): + ariaLabel: 'cool link' + } + ] + } +} +``` + +```ts +interface SocialLink { + icon: SocialLinkIcon + link: string + ariaLabel?: string +} + +type SocialLinkIcon = + | 'discord' + | 'facebook' + | 'github' + | 'instagram' + | 'linkedin' + | 'mastodon' + | 'npm' + | 'slack' + | 'twitter' + | 'x' + | 'youtube' + | { svg: string } +``` + +## footer + +- Tipo: `Footer` +- Se puede superponer por página mediante [frontmatter](./frontmatter-config#footer) + +Configuración de pie de página. Puede agregar un mensaje o texto de derechos de autor en el pie de página; sin embargo, solo se mostrará cuando la página no contenga una barra lateral. Esto se debe a preocupaciones de diseño. + +```ts +export default { + themeConfig: { + footer: { + message: 'Publicado bajo la licencia MIT.', + copyright: 'Derechos de autor © 2019-presente Evan You' + } + } +} +``` + +```ts +export interface Footer { + message?: string + copyright?: string +} +``` + +## editLink + +- Tipo: `EditLink` +- Se puede superponer por página mediante [frontmatter](./frontmatter-config#editlink) + +_EditLink_ le permite mostrar un enlace para editar la página en los servicios de administración Git, como GitHub o GitLab. Consulte [Tema por defecto: Editar Link](./default-theme-edit-link) para más detalles. + +```ts +export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'Editar esta página en GitHub' + } + } +} +``` + +```ts +export interface EditLink { + pattern: string + text?: string +} +``` + +## lastUpdated + +- Tipo: `LastUpdatedOptions` + +Permite la personalización del formato de fecha y texto actualizado por ultima vez. + +```ts +export default { + themeConfig: { + lastUpdated: { + text: 'Actualizado en', + formatOptions: { + dateStyle: 'full', + timeStyle: 'medium' + } + } + } +} +``` + +```ts +export interface LastUpdatedOptions { + /** + * @default 'Last updated' + */ + text?: string + + /** + * @default + * { dateStyle: 'short', timeStyle: 'short' } + */ + formatOptions?: Intl.DateTimeFormatOptions & { forceLocale?: boolean } +} +``` + +## algolia + +- Tipo: `AlgoliaSearch` + +Una opción para dar soporte para buscar en su sitio de documentación usando [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Obtenga más información en [Tema predeterminado: Buscar](./default-theme-search). + +```ts +export interface AlgoliaSearchOptions extends DocSearchProps { + locales?: Record> +} +``` + +Ver todas las opciones [aquí](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts). + +## carbonAds {#carbon-ads} + +- Tipo: `CarbonAdsOptions` + +Una opción para mostrar [Carbon Ads](https://www.carbonads.net/). + +```ts +export default { + themeConfig: { + carbonAds: { + code: 'su-código-carbon', + placement: 'su-colocación-carbon' + } + } +} +``` + +```ts +export interface CarbonAdsOptions { + code: string + placement: string +} +``` + +Obtenga más información en [Tema Predeterminado: Carbon Ads](./default-theme-carbon-ads). + +## docFooter + +- Tipo: `DocFooter` + +Se puede utilizar para personalizar el texto que aparece encima de los enlaces anterior y siguiente. Útil si no estás escribiendo documentación en inglés. También se puede utilizar para desactivar globalmente los enlaces anteriores/siguientes. Si desea habilitar/deshabilitar selectivamente enlaces anteriores/siguientes, puede usar [frontmatter](./default-theme-prev-next-links). + +```ts +export default { + themeConfig: { + docFooter: { + prev: 'Página anterior', + next: 'Próxima página' + } + } +} +``` + +```ts +export interface DocFooter { + prev?: string | false + next?: string | false +} +``` + +## darkModeSwitchLabel + +- Tipo: `string` +- Estandar: `Appearance` + +Se puede utilizar para personalizar la etiqueta del botón del modo oscuro. Esta etiqueta solo se muestra en la vista móvil. + +## lightModeSwitchTitle + +- Tipo: `string` +- Estandar: `Switch to light theme` + +Se puede utilizar para personalizar el título del botón borrar que aparece al pasar el mouse. + +## darkModeSwitchTitle + +- Tipo: `string` +- Estandar: `Switch to dark theme` + +Se puede utilizar para personalizar el título del botón del modo oscuro que aparece al pasar el mouse. + +## sidebarMenuLabel + +- Tipo: `string` +- Estandar: `Menu` + +Se puede utilizar para personalizar la etiqueta del menú de la barra lateral. Esta etiqueta solo se muestra en la vista móvil. + +## returnToTopLabel + +- Tipo: `string` +- Estandar: `Return to top` + +Se puede utilizar para personalizar la etiqueta del botón Volver al principio. Esta etiqueta solo se muestra en la vista móvil. + +## langMenuLabel + +- Tipo: `string` +- Estandar: `Change language` + +Se puede utilizar para personalizar la etiqueta aria del botón de idioma en la barra de navegación. Esto sólo se usa si estás usando [i18n](../guide/i18n). + +## externalLinkIcon + +- Tipo: `boolean` +- Estandar: `false` + +Se debe mostrar um ícono de link externo junto a los enlaces externos en markdown. diff --git a/docs/es/reference/default-theme-edit-link.md b/docs/es/reference/default-theme-edit-link.md new file mode 100644 index 00000000..fc26f3d6 --- /dev/null +++ b/docs/es/reference/default-theme-edit-link.md @@ -0,0 +1,60 @@ +# Editar Link {#edit-link} + +## Configuración a nivel de sitio {#site-level-config} + +Editar enlace le permite mostrar un enlace para editar la página con servicios de administración de Git como GitHub o GitLab. Para habilitar, agregue la opción `themeConfig.editLink` en su configuración. + +```js +export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path' + } + } +} +``` + +La opción `pattern` define una estructura de URL para el enlace, y `:path` se reemplaza con la misma ruta de la página + +También puedes poner una función pura que acepte [`PageData`](./runtime-api#usedata) como argumento y retorna una URL en string. + +```js +export default { + themeConfig: { + editLink: { + pattern: ({ filePath }) => { + if (filePath.startsWith('packages/')) { + return `https://github.com/acme/monorepo/edit/main/${filePath}` + } else { + return `https://github.com/acme/monorepo/edit/main/docs/${filePath}` + } + } + } + } +} +``` + +Esto no debería generar efectos secundarios ni acceder a nada fuera de su alcance, ya que será serializado y ejecutado en el navegador. + +De forma predeterminada, esto agregará el enlace con el texto 'Editar esta página' al final de la página de documentación. Puedes personalizar este texto configurando la opción `text`. + +```js +export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'Edite la página en GitHub' + } + } +} +``` + +## Configuración Frontmatter {#frontmatter-config} + +La funcionalidad se puede desactivar por página utilizando la opción `editLink` en frontmatter: + +```yaml +--- +editLink: false +--- +``` diff --git a/docs/es/reference/default-theme-footer.md b/docs/es/reference/default-theme-footer.md new file mode 100644 index 00000000..538a039e --- /dev/null +++ b/docs/es/reference/default-theme-footer.md @@ -0,0 +1,53 @@ +# Pie de página {#footer} + +VitePress mostrará un pie de página global en la parte inferior de la página cuando `themeConfig.footer` está presente. + +```ts +export default { + themeConfig: { + footer: { + message: 'Publicado bajo la licencia MIT.', + copyright: 'Derechos de autor © 2019-present Evan You' + } + } +} +``` + +```ts +export interface Footer { + // El mensaje mostrado justo antes del copyright. + message?: string + + // El texto real de copyright. + copyright?: string +} +``` + +La configuración anterior también admite cadenas HTML. Entonces, por ejemplo, si desea configurar el texto de su pie de página para que tenga algunos enlaces, puede ajustar la configuración de la siguiente manera: + +```ts +export default { + themeConfig: { + footer: { + message: 'Publicado bajo Licencia MIT.', + copyright: 'Derechos de autor © 2019-present Evan You' + } + } +} +``` + +::: warning +Solo se utilizan elementos _inline_ será utilizado en `message` y `copyright` tal como se presenta dentro del elemento `

`. Si desea agregar elementos de tipo _block_, considere usar un _slot_ [`layout-bottom`](../guide/extending-default-theme#layout-slots). +::: + +Tenga en cuenta que el pie de página no se mostrará cuando la [Barra Lateral](./default-theme-sidebar) es visible. + +## Configuración Frontmatter {#frontmatter-config} + +Esto se puede desactivar por página usando la opción `footer` en frontmatter: + +```yaml +--- +footer: false +--- +``` diff --git a/docs/es/reference/default-theme-home-page.md b/docs/es/reference/default-theme-home-page.md new file mode 100644 index 00000000..70dbdfcd --- /dev/null +++ b/docs/es/reference/default-theme-home-page.md @@ -0,0 +1,168 @@ +# Página Inicial {#home-page} + +El tema predeterminado de VitePress proporciona un diseño de página de inicio, que también puedes ver en uso [en la página de inicio de este sitio web](../). Puedes usarlo en cualquiera de sus páginas especificando `layout: home` en [frontmatter](./frontmatter-config). + +```yaml +--- +layout: home +--- +``` + +Sin embargo, esta opción por sí sola no sirve de mucho. Puede agregar varias "secciones" predefinidas diferentes a la página de inicio configurando opciones adicionales como `hero` y `features`. + +## Sección Hero {#hero-section} + +La sección _Hero_ queda en la parte superior de la página de inicio. Asi es como se puede configurar la sección _Hero_. + +```yaml +--- +layout: home + +hero: + name: VitePress + text: Generador de sitios web estáticos con Vite & Vue. + tagline: Lorem ipsum... + image: + src: /logo.png + alt: VitePress + actions: + - theme: brand + text: Iniciar + link: /guide/what-is-vitepress + - theme: alt + text: Ver en GitHub + link: https://github.com/vuejs/vitepress +--- +``` + +```ts +interface Hero { + // El string que se muestra encima del `text`. Viene con el color de la marca + // y se espera que sea breve, como el nombre del producto. + name?: string + + // El texto principal de la sección de hero. + // Esto se definirá como un tag `h1`. + text: string + + // Eslogan que se muestra abajo del `text`. + tagline?: string + + // La imagen se muestra junto al área de texto y eslogan. + image?: ThemeableImage + + // Botones accionables para mostrar en la sección principal de la página de inicio. + actions?: HeroAction[] +} + +type ThemeableImage = + | string + | { src: string; alt?: string } + | { light: string; dark: string; alt?: string } + +interface HeroAction { + // Tema de color de botón. Estándar: `brand`. + theme?: 'brand' | 'alt' + + // Etiqueta del botón. + text: string + + // Destino del enlace del botón. + link: string + + // Atributo target del link. + target?: string + + // Atributo rel del link. + rel?: string +} +``` + +### Personalizando el color del nombre {#customizing-the-name-color} + +VitePress usa el color de la marca (`--vp-c-brand-1`) para `name`. Sin embargo, puedes personalizar este color anulando la variable `--vp-home-hero-name-color`. + +```css +:root { + --vp-home-hero-name-color: blue; +} +``` + +También puedes personalizarlo aún más combinando `--vp-home-hero-name-background` para dar al `name` un color degradado. + +```css +:root { + --vp-home-hero-name-color: transparent; + --vp-home-hero-name-background: -webkit-linear-gradient(120deg, #bd34fe, #41d1ff); +} +``` + +## Sección de caracteristicas {#features-section} + +En la sección de funciones, puede enumerar cualquier cantidad de funciones que desee mostrar inmediatamente después de la sección. _Hero_. Para configurarlo seleccione la opción `features` para el frontmatter. + +Puede proporcionar un icono para cada función, que puede ser un emoji o cualquier tipo de imagen. Cuando el icono configurado es una imagen (svg, png, jpeg...), debes proporcionar al ícono el ancho y alto apropiados; También puedes proporcionar la descripción, su tamaño intrínseco y sus variantes para temas oscuros y claros cuando sea necesario. + +```yaml +--- +layout: home + +features: + - icon: 🛠️ + title: Sencillo y minimalista, siempre + details: Lorem ipsum... + - icon: + src: /cool-feature-icon.svg + title: Otra caracteristica interesante + details: Lorem ipsum... + - icon: + dark: /dark-feature-icon.svg + light: /light-feature-icon.svg + title: Otra caracteristica interesante + details: Lorem ipsum... +--- +``` + +```ts +interface Feature { + // Muestra el icono en cada cuadro de función. + icon?: FeatureIcon + + // Título de la caracteristica. + title: string + + // Detalles de la caracteristicas. + details: string + + // Enlace al hacer clic en el componente de funcionalidad + // El vínculo puede ser interno o externo. + // + // ej. `guide/reference/default-theme-home-page` ou `https://example.com` + link?: string + + // Texto del enlace que se mostrará dentro del componente de funcionalidad. + // Mejor usado con opción `link`. + // + // ej. `Sepa más`, `Visitar página`, etc. + linkText?: string + + // Atributo rel de enlace para la opción `link`. + // + // ej. `external` + rel?: string + + // Atributo de destino del enlace para la opción `link`. + target?: string +} + +type FeatureIcon = + | string + | { src: string; alt?: string; width?: string; height: string } + | { + light: string + dark: string + alt?: string + width?: string + height: string + } +``` diff --git a/docs/es/reference/default-theme-last-updated.md b/docs/es/reference/default-theme-last-updated.md new file mode 100644 index 00000000..e1ac4022 --- /dev/null +++ b/docs/es/reference/default-theme-last-updated.md @@ -0,0 +1,27 @@ +# Última Actualización {#last-updated} + +La hora en que se actualizó el contenido por última vez se mostrará en la esquina inferior derecha de la página. Para habilitar, agregue la opción `lastUpdated` en su confirguración. + +::: tip +Necesitas hacer un _commit_ en el archivo markdown para ver el clima actualizado. +::: + +## Configuración a nivel de sitio {#site-level-config} + +```js +export default { + lastUpdated: true +} +``` + +## Configuración Frontmatter {#frontmatter-config} + +Esto se puede desactivar por página usando la opción `lastUpdated` en frontmatter: + +```yaml +--- +lastUpdated: false +--- +``` + +Consulte [Tema Personalizado: Última Actualización](./default-theme-config#lastupdated) para obtener más. Cualquier valor positivo a nivel de tema también habilitará la funcionalidad a menos que esté explícitamente deshabilitado a nivel de página o sitio. diff --git a/docs/es/reference/default-theme-layout.md b/docs/es/reference/default-theme-layout.md new file mode 100644 index 00000000..10e910c0 --- /dev/null +++ b/docs/es/reference/default-theme-layout.md @@ -0,0 +1,62 @@ +# Layout {#layout} + +Puedes elegir el layout de la página definiendo una opción de `layout` para el [frontmatter](./frontmatter-config) De la página. Hay tres opciones de layout: `doc`, `page` y `home`. Si no se especifica nada, la página será tratada como una página. `doc`. + +```yaml +--- +layout: doc +--- +``` + +## Layout del documento {#doc-layout} + +La opción `doc` es el layout predeterminado y aplica estilo a todo el contenido de Markdown el aspecto de "documentación". Funciona agrupando todo el contenido en la clase CSS `vp-doc`, y aplicando estilos a los elementos debajo de ella. + +Casi todos los elementos genéricos como `p` o `h2`, recibirá un estilo especial. Por tanto, recuerda que si añades algún HTML contenido personalizado dentro del contenido Markdown, también se verá afectado por estos estilos. + +También proporciona recursos de documentación específicos que se enumeran a continuación. Estas funciones solo están habilitadas en este layout. + +- Editar link +- Links Anterior y próximo. +- _Outline_ +- [Carbon Ads](./default-theme-carbon-ads) + +## Layout de la Página {#page-layout} + +La opción `page` se trata como una 'página en blanco'. Markdown aún se procesará y todo [Extensiones Markdown](../guide/markdown) funcionará de la misma manera que el layout `doc`, pero esto no recibirá ningún estilo predeterminado. + +El layout de la página le permitirá diseñar todo sin que el tema de VitePress afecte el marcado. Esto es útil cuando desea crear su propia página personalizada. + +Tenga en cuenta que incluso en este mismo layout, la barra lateral seguirá apareciendo si la página tiene una configuración de barra lateral correspondiente. + +## Layout de Home {#home-layout} + +La opción `home` gerará un modelo de _"Homepage"_. En este layout podrás definir opciones extras, como `hero` y `features`, para personalizar todavá más el contenido. Visite [Tema predeterminado: Página Inicial](./default-theme-home-page) para obter más detalles. + +## Sin Layout {#no-layout} + +Si no quieres ningún diseño, puedes pasar `layout: false` a través del frontmatter. Esta opción es útil si deseas una página de destino completamente personalizable (sin barra lateral, barra de navegacón o pie de página por defecto). + +## Layout Personalizado {#custom-layout} + +También puedes usar un layout personalizado: + +```md +--- +layout: foo +--- +``` + +Esto buscará un componente llamado `foo` registrado en contexto. Por ejemplo, puede registrar su componente globalmente en `.vitepress/theme/index.ts`: + +```ts +import DefaultTheme from 'vitepress/theme' +import Foo from './Foo.vue' + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('foo', Foo) + } +} +``` diff --git a/docs/es/reference/default-theme-nav.md b/docs/es/reference/default-theme-nav.md new file mode 100644 index 00000000..d244cba5 --- /dev/null +++ b/docs/es/reference/default-theme-nav.md @@ -0,0 +1,162 @@ +# Navegación {#nav} + +Refiriéndose a la barra de navegación que se muestra en la parte superior de la página. Contiene el título del sitio, enlaces del menú global, etc. + +## Título y logotipo del sitio {#site-title-and-logo} + +Por defecto, la navegación muestra el título del sitio que hace referencia al valor de [`config.title`](./site-config#title). Si desea cambiar lo que se muestra en la navegación, puede configurar un texto personalizado en el `themeConfig.siteTitle`. + +```js +export default { + themeConfig: { + siteTitle: 'Mi Título Personalizado' + } +} +``` + +Si tiene un logotipo para su sitio web, puede mostrarlo pasando la ruta a la imagen. Debes colocar el logo directamente dentro de la carpeta. `public`, y establezca la ruta absoluta hacia él. + +```js +export default { + themeConfig: { + logo: '/my-logo.svg' + } +} +``` + +Cuando agrega un logotipo, se muestra junto con el título del sitio. Si su logotipo tiene todo lo que necesita y desea ocultar el texto del título, configure `false` en la opción `siteTitle`. + +```js +export default { + themeConfig: { + logo: '/my-logo.svg', + siteTitle: false + } +} +``` + +También puedes pasar un objeto como logotipo si quieres agregar un atributo. `alt` o personalizarlo según el modo claro/oscuro. Consultar [`themeConfig.logo`](./default-theme-config#logo) para obtener más detalles. + +## Links de Navegación {#navigation-links} + +Puedes configurar la opción `themeConfig.nav` para añadir enlaces a tu navegación. + +```js +export default { + themeConfig: { + nav: [ + { text: 'Guia', link: '/guide' }, + { text: 'Configuración', link: '/config' }, + { text: 'Registro de Cambios', link: 'https://github.com/...' } + ] + } +} +``` + +`text` es el texto que se muestra en la navegación, y el `link` es el link al que será navegando cuando se hace click en el texto. Para el enlace, establezca la ruta al archivo sin el prefijo `.md` y siempre comenzar por `/`. + +Links de navegación también pueden ser menus _dropdown_. Para hacer eso, establezca la clave de `items` en la opción del link. + +```js +export default { + themeConfig: { + nav: [ + { text: 'Guia', link: '/guide' }, + { + text: 'Menú Dropdown', + items: [ + { text: 'Item A', link: '/item-1' }, + { text: 'Item B', link: '/item-2' }, + { text: 'Item C', link: '/item-3' } + ] + } + ] + } +} +``` + +Tenga en cuenta que el titulo del menú _dropdown_ (`Menu Dropdown` en el ejemplo anterior) no puede tener una propiedad `link`, ya que se convierte en un botón para abrir el cuadro del dialogo dropdown. + +También puedes agregar "secciones" a los elementos del menú _dropdown_ pasando más elementos anidados. + +```js +export default { + themeConfig: { + nav: [ + { text: 'Guia', link: '/guia' }, + { + text: 'Menú Dropdown', + items: [ + { + // Título da seção. + text: 'Título de la sección A', + items: [ + { text: 'Item A de la sección A', link: '...' }, + { text: 'Item B de la sección B', link: '...' } + ] + } + ] + }, + { + text: 'Menú Dropdown', + items: [ + { + // También puedes omitir el título + items: [ + { text: 'Item A da Seção A', link: '...' }, + { text: 'Item B da Seção B', link: '...' } + ] + } + ] + } + ] + } +} +``` + +### Personaliza el estado "activo" del link {#customize-link-s-active-state} + +Los elementos del menú de navegación se resaltarán cuando la página actual esté en la ruta correspondiente. Si desea personalizar la ruta que debe coincidir, establezca la propiedad `activeMatch` el regex como um valor en string. + +```js +export default { + themeConfig: { + nav: [ + // Este link esta en estado activo cuando + // el usuario esta en el camino `/config/`. + { + text: 'Guia', + link: '/guide', + activeMatch: '/config/' + } + ] + } +} +``` + +::: warning +`activeMatch` Debería ser un string regex, pero deberías definirla como un string. No podemos usar un objeto RegExp real aquí porque no es serializable durante el tiempo de construcción. +::: + +### Personalizar los atributos "target" y "rel" de links {#customize-link-s-target-and-rel-attributes} + +Por defecto, VitePress determina automáticamente lod atributos `target` y `rel` en función de si existe un enlace externo o no. Pero si quieres, también puedes personalizarlos. + +```js +export default { + themeConfig: { + nav: [ + { + text: 'Merchandise', + link: 'https://www.thegithubshop.com/', + target: '_self', + rel: 'sponsored' + } + ] + } +} +``` + +## Links Scociales {#social-links} + +Consulte [`socialLinks`](./default-theme-config#sociallinks). diff --git a/docs/es/reference/default-theme-prev-next-links.md b/docs/es/reference/default-theme-prev-next-links.md new file mode 100644 index 00000000..6c10c7bc --- /dev/null +++ b/docs/es/reference/default-theme-prev-next-links.md @@ -0,0 +1,43 @@ +# Links Anterior y Próximo {#prev-next-links} + +Puede personalizar el texto y el enlace de los botones Anterior y Siguiente que se muestran en la parte inferior de la página. Esto es útil cuando desea mostrar un texto diferente al que tiene en la barra lateral. Además, puede resultarle útil desactivar el pie de página o el enlace a la página para que no se incluya en la barra lateral. + +## prev + +- Tipo: `string | false | { text?: string; link?: string }` + +- Detalles: + + Especifica el text/enlace que se mostrará en el enlace a la página anterior. Si no ve esto al principio, el text/enlace se deducirá de la configuración de la barra lateral. + +- Ejemplos: + + - Para personalizar solo texto: + + ```yaml + --- + prev: 'Iniciar | Markdown' + --- + ``` + + - Para personalizar ambos texto y link: + + ```yaml + --- + prev: + text: 'Markdown' + link: '/guide/markdown' + --- + ``` + + - Para esconder la página anterior: + + ```yaml + --- + prev: false + --- + ``` + +## next + +Igual que el `prev` pero para la página siguiente. diff --git a/docs/es/reference/default-theme-search.md b/docs/es/reference/default-theme-search.md new file mode 100644 index 00000000..10235382 --- /dev/null +++ b/docs/es/reference/default-theme-search.md @@ -0,0 +1,379 @@ +--- +outline: deep +--- + +# Buscar {#search} + +## Busqueda local {#local-search} + +VitePress admite la búsqueda de texto completo utilizando un índice en el navegador gracias a [minisearch](https://github.com/lucaong/minisearch/). Para habilitar esta función, simplemente configure la opción `themeConfig.search.provider` como `'local'` en el archivo `.vitepress/config.ts`: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local' + } + } +}) +``` + +Resultado de ejemplo: + +![captura de pantalla del modo de búsqueda](/search.png) + +Alternativamente, puedes usar [Algolia DocSearch](#algolia-search) o algunos complementos comunitarios como o . + +### i18n {#local-search-i18n} + +Puede utilizar una configuración como esta para utilizar la búsqueda multilingüe: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + locales: { + zh: { + translations: { + button: { + buttonText: '搜索文档', + buttonAriaLabel: '搜索文档' + }, + modal: { + noResultsText: '无法找到相关结果', + resetButtonTitle: '清除查询条件', + footer: { + selectText: '选择', + navigateText: '切换' + } + } + } + } + } + } + } + } +}) +``` + +### Opciones MiniSearch {#mini-search-options} + +Puedes configurar MiniSearch de esta manera: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + miniSearch: { + /** + * @type {Pick} + */ + options: { + /* ... */ + }, + /** + * @type {import('minisearch').SearchOptions} + * @default + * { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } } + */ + searchOptions: { + /* ... */ + } + } + } + } + } +}) +``` + +Obtenga más información en [documentación de MiniSearch](https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html). + +### Presentador de contenido personalizado {#custom-content-renderer} + +Puedes personalizar la función utilizada para presentar el contenido de rebajas antes de indexarlo: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + /** + * @param {string} src + * @param {import('vitepress').MarkdownEnv} env + * @param {import('markdown-it')} md + */ + _render(src, env, md) { + // retorne un string HTML + } + } + } + } +}) +``` + +Esta función se eliminará de los datos del sitio web en el lado del cliente, por lo que podrá utilizar las API de Node.js en ella. + +#### Ejemplo: Excluir páginas de la busqueda {#example-excluding-pages-from-search} + +Puedes excluir páginas de la busqueda adicionando `search: false` al principio de la página. Alternativamente: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + _render(src, env, md) { + const html = md.render(src, env) + if (env.frontmatter?.search === false) return '' + if (env.relativePath.startsWith('algum/caminho')) return '' + return html + } + } + } + } +}) +``` + +::: warning Nota +En este caso, una función `_render` se proporciona, es necesario manipular el `search: false` desde el frente por su cuenta. Además, el objeto `env` no estará completamente poblado antes que `md.render` se llama, luego verifica las propiedades opcionales `env`, como `frontmatter`, debe hacerse después de eso. +::: + +#### Ejemplo: Transformar contenido - agregar anclajes {#example-transforming-content-adding-anchors} + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + _render(src, env, md) { + const html = md.render(src, env) + if (env.frontmatter?.title) + return md.render(`# ${env.frontmatter.title}`) + html + return html + } + } + } + } +}) +``` + +## Busqueda de Algolia {#algolia-search} + +VitePress admite la búsqueda en su sitio de documentación utilizando [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Consulte su guía de introducción. en tu archivo `.vitepress/config.ts`, Deberá proporcionar al menos lo siguiente para que funcione: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...' + } + } + } +}) +``` + +### i18n {#algolia-search-i18n} {#algolia-search-i18n} + +Puedes utilizar una configuración como esta para utilizar la búsqueda multilingüe: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + locales: { + zh: { + placeholder: '搜索文档', + translations: { + button: { + buttonText: '搜索文档', + buttonAriaLabel: '搜索文档' + }, + modal: { + searchBox: { + resetButtonTitle: '清除查询条件', + resetButtonAriaLabel: '清除查询条件', + cancelButtonText: '取消', + cancelButtonAriaLabel: '取消' + }, + startScreen: { + recentSearchesTitle: '搜索历史', + noRecentSearchesText: '没有搜索历史', + saveRecentSearchButtonTitle: '保存至搜索历史', + removeRecentSearchButtonTitle: '从搜索历史中移除', + favoriteSearchesTitle: '收藏', + removeFavoriteSearchButtonTitle: '从收藏中移除' + }, + errorScreen: { + titleText: '无法获取结果', + helpText: '你可能需要检查你的网络连接' + }, + footer: { + selectText: '选择', + navigateText: '切换', + closeText: '关闭', + searchByText: '搜索提供者' + }, + noResultsScreen: { + noResultsText: '无法找到相关结果', + suggestedQueryText: '你可以尝试查询', + reportMissingResultsText: '你认为该查询应该有结果?', + reportMissingResultsLinkText: '点击反馈' + } + } + } + } + } + } + } + } +}) +``` + +[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} + +A continuación se muestra un ejemplo de la configuración que utiliza este sitio: + +```ts +new Crawler({ + appId: '...', + apiKey: '...', + rateLimit: 8, + startUrls: ['https://vitepress.dev/'], + renderJavaScript: false, + sitemaps: [], + exclusionPatterns: [], + ignoreCanonicalTo: false, + discoveryPatterns: ['https://vitepress.dev/**'], + schedule: 'at 05:10 on Saturday', + actions: [ + { + indexName: 'vitepress', + pathsToMatch: ['https://vitepress.dev/**'], + recordExtractor: ({ $, helpers }) => { + return helpers.docsearch({ + recordProps: { + lvl1: '.content h1', + content: '.content p, .content li', + lvl0: { + selectors: '', + defaultValue: 'Documentation' + }, + lvl2: '.content h2', + lvl3: '.content h3', + lvl4: '.content h4', + lvl5: '.content h5' + }, + indexHeadings: true + }) + } + } + ], + initialIndexSettings: { + vitepress: { + attributesForFaceting: ['type', 'lang'], + attributesToRetrieve: ['hierarchy', 'content', 'anchor', 'url'], + attributesToHighlight: ['hierarchy', 'hierarchy_camel', 'content'], + attributesToSnippet: ['content:10'], + camelCaseAttributes: ['hierarchy', 'hierarchy_radio', 'content'], + searchableAttributes: [ + 'unordered(hierarchy_radio_camel.lvl0)', + 'unordered(hierarchy_radio.lvl0)', + 'unordered(hierarchy_radio_camel.lvl1)', + 'unordered(hierarchy_radio.lvl1)', + 'unordered(hierarchy_radio_camel.lvl2)', + 'unordered(hierarchy_radio.lvl2)', + 'unordered(hierarchy_radio_camel.lvl3)', + 'unordered(hierarchy_radio.lvl3)', + 'unordered(hierarchy_radio_camel.lvl4)', + 'unordered(hierarchy_radio.lvl4)', + 'unordered(hierarchy_radio_camel.lvl5)', + 'unordered(hierarchy_radio.lvl5)', + 'unordered(hierarchy_radio_camel.lvl6)', + 'unordered(hierarchy_radio.lvl6)', + 'unordered(hierarchy_camel.lvl0)', + 'unordered(hierarchy.lvl0)', + 'unordered(hierarchy_camel.lvl1)', + 'unordered(hierarchy.lvl1)', + 'unordered(hierarchy_camel.lvl2)', + 'unordered(hierarchy.lvl2)', + 'unordered(hierarchy_camel.lvl3)', + 'unordered(hierarchy.lvl3)', + 'unordered(hierarchy_camel.lvl4)', + 'unordered(hierarchy.lvl4)', + 'unordered(hierarchy_camel.lvl5)', + 'unordered(hierarchy.lvl5)', + 'unordered(hierarchy_camel.lvl6)', + 'unordered(hierarchy.lvl6)', + 'content' + ], + distinct: true, + attributeForDistinct: 'url', + customRanking: [ + 'desc(weight.pageRank)', + 'desc(weight.level)', + 'asc(weight.position)' + ], + ranking: [ + 'words', + 'filters', + 'typo', + 'attribute', + 'proximity', + 'exact', + 'custom' + ], + highlightPreTag: '', + highlightPostTag: '', + minWordSizefor1Typo: 3, + minWordSizefor2Typos: 7, + allowTyposOnNumericTokens: false, + minProximity: 1, + ignorePlurals: true, + advancedSyntax: true, + attributeCriteriaComputedByMinProximity: true, + removeWordsIfNoResults: 'allOptional' + } + } +}) +``` + + diff --git a/docs/es/reference/default-theme-sidebar.md b/docs/es/reference/default-theme-sidebar.md new file mode 100644 index 00000000..05dd42f3 --- /dev/null +++ b/docs/es/reference/default-theme-sidebar.md @@ -0,0 +1,217 @@ +# Barra Lateral {#sidebar} + +La barra lateral es el bloque de navegación principal de su documentación. Puede configurar el menú de la barra lateral en [`themeConfig.sidebar`](./default-theme-config#sidebar). + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Guia', + items: [ + { text: 'Introducción', link: '/introduction' }, + { text: 'Iniciando', link: '/getting-started' }, + ... + ] + } + ] + } +} +``` + +## Conceptos básicos {#the-basics} + +La forma más sencilla del menú de la barra lateral es pasar una único _array_ de links. El elemento de primer nivel define la "sección" de la barra latera. debe contener `text`, cuál es el título de la sección, y `items` que son los propios enlaces de navegación. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Título de la sección A', + items: [ + { text: 'Item A', link: '/item-a' }, + { text: 'Item B', link: '/item-b' }, + ... + ] + }, + { + text: 'Título de la sección B', + items: [ + { text: 'Item C', link: '/item-c' }, + { text: 'Item D', link: '/item-d' }, + ... + ] + } + ] + } +} +``` + +Cada `link` debe especificar la ruta al archivo en sí comenzando con `/`. +Si agrega una barra al final del enlace, mostrará el `index.md` del directorio correspondiente. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Guia', + items: [ + // Esto muestra la página `/guide/index.md`. + { text: 'Introducción', link: '/guide/' } + ] + } + ] + } +} +``` + +Puede anidar aún más elementos de la barra lateral hasta 6 niveles de profundidad contando desde el nivel raíz. Tenga en cuenta que los niveles superiores a 6 se ignorarán y no se mostrarán en la barra lateral. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Nivel 1', + items: [ + { + text: 'Nivel 2', + items: [ + { + text: 'Nivel 3', + items: [ + ... + ] + } + ] + } + ] + } + ] + } +} +``` + +## Varias Barras Laterales {#multiple-sidebars} + +Puedes mostrar una barra lateral diferente según la ruta de la página. Por ejemplo, como se muestra en este sitio, es posible que desee crear secciones separadas de contenido en su documentación, como la página "Guía" y la página "Configuración". + +Para hacer esto, primero organice sus páginas en directorios para cada sección deseada: + +``` +. +├─ guide/ +│ ├─ index.md +│ ├─ one.md +│ └─ two.md +└─ config/ + ├─ index.md + ├─ three.md + └─ four.md +``` + +Luego actualice su configuración para definir su barra lateral para cada sección. Esta vez debes pasar un objeto en lugar de un array. + +```js +export default { + themeConfig: { + sidebar: { + // Esta barra lateral se muestra cuando un usuario + // está en el directorio `guide`. + '/guide/': [ + { + text: 'Guia', + items: [ + { text: 'Índice', link: '/guide/' }, + { text: 'Um', link: '/guide/one' }, + { text: 'Dois', link: '/guide/two' } + ] + } + ], + + // Esta barra lateral se muestra cuando un usuario + // está en el directorio `config`. + '/config/': [ + { + text: 'Configuración', + items: [ + { text: 'Índice', link: '/config/' }, + { text: 'Tres', link: '/config/three' }, + { text: 'Cuatro', link: '/config/four' } + ] + } + ] + } + } +} +``` + +## Grupos Retráctiles en la Barra Lateral {#collapsible-sidebar-groups} + +Adicionando una opción `collapsed` al grupo de la barra lateral, muestra un botón para ocultar/mostrar cada sección + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Título de la sección A', + collapsed: false, + items: [...] + } + ] + } +} +``` + +Todas las secciones están 'abiertas' de forma predeterminada. Si desea que estén 'cerrados' al cargar la página inicial, configure la opción `collapsed` como `true`. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Título de la sección A', + collapsed: true, + items: [...] + } + ] + } +} +``` + +## `useSidebar` + +Devuelve datos relacionados con la barra lateral. El objeto devuelto tiene el siguiente tipo: + +```ts +export interface DocSidebar { + isOpen: Ref + sidebar: ComputedRef + sidebarGroups: ComputedRef + hasSidebar: ComputedRef + hasAside: ComputedRef + leftAside: ComputedRef + isSidebarEnabled: ComputedRef + open: () => void + close: () => void + toggle: () => void +} +``` + +**Exemplo:** + +```vue + + + +``` diff --git a/docs/es/reference/default-theme-team-page.md b/docs/es/reference/default-theme-team-page.md new file mode 100644 index 00000000..1f6492a8 --- /dev/null +++ b/docs/es/reference/default-theme-team-page.md @@ -0,0 +1,258 @@ + + +# Página de Equipo {#team-page} + +Si deseas presentar a tu equipo, puedes utilizar componentes del equipo para crear la página del equipo. Hay dos formas de utilizar estos componentes. Una es incrustarlo en la página del documento y otra es crear una página de equipo completa. + +## Mostrar miembros del equipo en una página {#show-team-members-in-a-page} + +Puedes usar el componente `` expuesto en `vitepress/theme` para mostrar una lista de los miembros del equipo en cualquier página. + +```html + + +# Nuestro equipo + +Saluda a nuestro increible equipo. + + +``` + +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 componente `` 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). + +Incrustar miembros del equipo en la página del documento es bueno para equipos pequeños donde tener una página de equipo dedicada completa puede ser demasiado, o introducir miembros parciales como referencia al contexto de la documentación. + +Si tienes una gran cantidad de miembros o simplemente deseas más espacio para exhibir a los miembros del equipo, considere [crear una página de equipo completa.](#create-a-full-team-page) + +## Creando una página de equipo completa {#create-a-full-team-page} + +En lugar de agregar miembros del equipo a la página del documento, también puede crear una página de equipo completa, del mismo modo que puede crear una [Página Inicial](./default-theme-home-page) personalizada. + +Para crear una página de equipo, primero cree un nuevo md. El nombre del archivo no importa, pero aquí lo llamaremos `team.md`. En este archivo, configure la opción `layout: page` desde frontmatter, y luego puedes componer la estructura de tu página usando componentes `TeamPage`. + +```html +--- +layout: page +--- + + + + + + + + + +``` + +Al crear una página de equipo completa, recuerde agrupar todos los componentes con el componente ``. Este componente garantizará que todos los componentes anidados relacionados con el equipo obtengan la estructura de diseño adecuada, como los espacios. + +El componente `` adiciona la sección de título de la página. El título es `

`. Use los _slots_ `#title` y `#lead` para poder documentar sobre su equipo. + +`` funciona igual que cuando se usa en una página de documento. Mostrará la lista de miembros. + +### Agregar secciones para dividir a los miembros del equipo {#add-sections-to-divide-team-members} + +Puede agregar "secciones" a la página de su equipo. Por ejemplo, puede tener diferentes tipos de miembros del equipo, como miembros del equipo central y socios de la comunidad. Puede dividir a estos miembros en secciones para explicar mejor las funciones de cada grupo. + +Para poder hacerlo, agregue al componente `` al archivo `team.md` que creamos anteriormente. + +```html +--- +layout: page +--- + + + + + + + + + + + + + + +``` + +El componente `` Puede tener los _slots_ `#title` y `#lead` similares al componente `VPTeamPageTitle`, y también al _slot_ `#members` para mostrar a los miembros del equipo. + +Recuerde colocar el componente `` dentro del _slot_ `#members`. + +## `` + +El componente `` muestra una determinada lista de miembros. + +```html + +``` + +```ts +interface Props { + // Tamaño de cada miembro. El valor predeterminado es `medium`. + size?: 'small' | 'medium' + + // Lista de miembros que se mostrará. + members: TeamMember[] +} + +interface TeamMember { + // Imagen de avatar de miembro. + avatar: string + + // Nombre del miembro. + name: string + + // Título a ser mostrado a bajo del nombre del miembro. + // Ej.: Desarrollador, Ingeniero de Software, etc. + title?: string + + // Organización a la que pertenece al miembro. + org?: string + + // URL de la organización. + orgLink?: string + + // Descripción del miembro. + desc?: string + + // Links sociales, por ejemplo, GitHub, Twitter, etc. + // Puedes pasar un objeto de Links Sociales aquí. + // Vea: https://vitepress.dev/reference/default-theme-config.html#sociallinks + links?: SocialLink[] + + // URL de la página del patrocinador del miembro. + sponsor?: string + + // Texto para enlace del patrocinador. El valor predeterminado es 'Sponsor'. + actionText?: string +} +``` + +## `` + +El componente raíz al crear una página de equipo completa. Sólo acepta una _slot_. Aplicará estilo a todos los componentes anteriores relacionados con el equipo. + +## `` + +Agrega la sección "título" a la página. Es mejor usarlo desde el principio debajo ``. Acepta los _slots_ `#title` y `#lead`. + +```html + + + + + + +``` + +## `` + +Crea una 'sección' en la página del equipo. Aceptar los _slots_ `#title`, `#lead` y `#members`. Puedes agregar tantas secciones como quieras dentro ``. + +```html + + ... + + + + + + +``` diff --git a/docs/es/reference/frontmatter-config.md b/docs/es/reference/frontmatter-config.md new file mode 100644 index 00000000..9032f42e --- /dev/null +++ b/docs/es/reference/frontmatter-config.md @@ -0,0 +1,221 @@ +--- +outline: deep +--- + +# Configuración Frontmatter {#frontmatter-config} + +Frontmatter permite la configuración basada en páginas. En cada archivo markdown, puede utilizar la configuración de frontmatter para anular las opciones de configuración a nivel de sitio o tema. Además, hay opciones de configuración que sólo se pueden establecer en frontmatter. + +Ejemplo de uso: + +```md +--- +title: Documentación con VitePress +editLink: true +--- +``` + +Puede acceder a los datos del frontmatter a través de la variable global `$frontmatter` en expresiones Vue: + +```md +{{ $frontmatter.title }} +``` + +## title + +- Tipo: `string` + +Título de la página. Es lo mismo que [config.title](./site-config#title), y anula la configuración a nivel de sitio. + +```yaml +--- +title: VitePress +--- +``` + +## titleTemplate + +- Tipo: `string | boolean` + +El sufijo del título. Es lo mismo que [config.titleTemplate](./site-config#titletemplate), y anula la configuración a nivel de sitio. + +```yaml +--- +title: VitePress +titleTemplate: Generador de sitios web estáticos con Vite & Vue +--- +``` + +## descripción + +- Tipo: `string` + +Descripción de la página. Es lo mismo que [config.description](./site-config#description), y anula la configuración a nivel de sitio. + +```yaml +--- +description: VitePress +--- +``` + +## head + +- Tipo: `HeadConfig[]` + +Especifica etiquetas de encabezado adicionales que se inyectarán en la página actual. Se agregarán después de las etiquetas principales inyectadas por la configuración a nivel de sitio. + +```yaml +--- +head: + - - meta + - name: description + content: hello + - - meta + - name: keywords + content: super duper SEO +--- +``` + +```ts +type HeadConfig = + | [string, Record] + | [string, Record, string] +``` + +## Solo Tema Predeterminado {#default-theme-only} + +Las siguientes opciones de frontmatter solo se aplican cuando se usa el tema predeterminado. + +### layout + +- Tipo: `doc | home | page` +- Predeterminado: `doc` + +Determina el layout de la página. + +- `doc` - Aplica estilos de documentación por defecto al contenido markdown. +- `home` - Layout especial para la "Página Inicial". Puedes agregar opciones extras como `hero` y `features` para crear rapidamente una hermosa página inicial. +- `page` - Se comporta de manera similar a `doc`, pero no aplica estilos al contenido. Útil cuando desea crear una página totalmente personalizada. + +```yaml +--- +layout: doc +--- +``` + +### hero + +Define el contenido de la sección _hero_ en la página inicial cuando `layout` está definido como `home`. Más detalles en [Tema Predeterminado: Página Inicial](./default-theme-home-page). + +### features + +Define los elementos que se mostrarán en la sección de características cuando `layout` está definido como `home`. Más detalles en [Tema Predeterminado: Página Inicial](./default-theme-home-page). + +### navbar + +- Tipo: `boolean` +- Predeterminado: `true` + +Se debe mostrar una [barra de navegación](./default-theme-nav). + +```yaml +--- +navbar: false +--- +``` + +### sidebar + +- Tipo: `boolean` +- Predeterminado: `true` + +Se debe mostrar una [barra lateral](./default-theme-sidebar). + +```yaml +--- +sidebar: false +--- +``` + +### aside + +- Tipo: `boolean | 'left'` +- Predeterminado: `true` + +Define la localización del componente aside en el layout `doc`. + +Configurar este valor como `false` evita que se muestre el elemento lateral.\ +Configurar este valor como `true` presenta el lado de la derecha.\ +Configurar este valor como `'left'` presenta el lado de la izquierda. + +```yaml +--- +aside: false +--- +``` + +### outline + +- Tipo: `number | [number, number] | 'deep' | false` +- Predeterminado: `2` + +Los niveles del encabezado en _outline_ que se mostrará para la página. Es lo mismo que [config.themeConfig.outline.level](./default-theme-config#outline), y anula el valor establecido en la configuración a nivel de sitio. + +### lastUpdated + +- Tipo: `boolean | Date` +- Predeterminado: `true` + +Se debe mostrar el texto de [última actualización](./default-theme-last-updated) en el pie de página de la página actual. Si se especifica una fecha y hora específicas, se mostrarán en lugar de la hora de la última modificación de git. + +```yaml +--- +lastUpdated: false +--- +``` + +### editLink + +- Tipo: `boolean` +- Predeterminado: `true` + +Se debe mostrar el [link de edición](./default-theme-edit-link) en el pie de página de la página actual. + +```yaml +--- +editLink: false +--- +``` + +### footer + +- Tipo: `boolean` +- Predeterminado: `true` + +Se debe mostrar el [pie de página](./default-theme-footer). + +```yaml +--- +footer: false +--- +``` + +### pageClass + +- Tipo: `string` + +Agrega un nombre de clase adicional a una página específica. + +```yaml +--- +pageClass: custom-page-class +--- +``` + +Luego puede personalizar los estilos para esta página específica en el archivo. `.vitepress/theme/custom.css`: + +```css +.custom-page-class { + /* estilos especificos de la página */ +} +``` diff --git a/docs/es/reference/runtime-api.md b/docs/es/reference/runtime-api.md new file mode 100644 index 00000000..21fec5a9 --- /dev/null +++ b/docs/es/reference/runtime-api.md @@ -0,0 +1,165 @@ +# API en Tiempo de Ejecución {#runtime-api} + +VitePress ofrece varias API integradas para permitir el acceso a los datos de la aplicación. VitePress también viene con algunos componentes integrados que se pueden utilizar globalmente. + +Los métodos auxiliares son importaciones globales de `vitepress` y se utilizan a menudo en componentes Vue de temas personalizados. Sin embargo, también se pueden utilizar dentro de páginas `.md` porque los archivos de rebajas se compilan en [Componentes de Archivo Único Vue (SFC)](https://vuejs.org/guide/scaling-up/sfc.html). + +Métodos que comienzan con `use*` indican que es una función de [API de Composición Vue 3](https://vuejs.org/guide/introduction.html#composition-api) ("Composable") que solo puede ser utilizada dentro de `setup()` o ` + + +``` + +## `useRoute` + +Devuelve el objeto de ruta actual con el siguiente tipo: + +```ts +interface Route { + path: string + data: PageData + component: Component | null +} +``` + +## `useRouter` + +Devuelve la instancia del enrutador VitePress para que pueda navegar mediante programación a otra página. + +```ts +interface Router { + /** + * Ruta atual. + */ + route: Route + /** + * Navegar para una nueva URL. + */ + go: (to?: string) => Promise + /** + * Llamado antes del cambio de ruta. Devuelve 'falso' para cancelar la navegación. + */ + onBeforeRouteChange?: (to: string) => Awaitable + /** + * Se llama antes de que se cargue el componente de la página (después de que se haya actualizado el estado del historial). + * atualizado). Retorne `false` para cancelar la navegación. + */ + onBeforePageLoad?: (to: string) => Awaitable + /** + * Llamado después del cambio de ruta. + */ + onAfterRouteChanged?: (to: string) => Awaitable +} +``` + +## `withBase` + +- **Tipo**: `(path: string) => string` + +agrega la [`base`](./site-config#base) configurada a una ruta URL determinada. Consulte también [Base URL](../guide/asset-handling#base-url). + +## `` + +El componente `` muestra el contenido de markdown renderizado. Útil [al crear tu propio tema](../guide/custom-theme). + +```vue + +``` + +## `` + +El componente `` muestra tu _slot_ solo del lado del cliente. + +Debido a que las aplicaciones VitePress se interpretan en el lado del servidor en Node.js cuando generan compilaciones estáticas, cualquier uso de Vue debe seguir los requisitos del código universal. En resumen, asegúrese de acceder solo a las API del navegador/DOM en ganchos `beforeMount` o `mounted`. + +Si está utilizando o demostrando componentes que no son compatibles con SSR (por ejemplo, contienen directivas personalizadas), puede incluirlos dentro del componente. `ClientOnly`. + +```vue-html + + + +``` + +- Relacionado: [Compatibilidad SSR](../guide/ssr-compat) + +## `$frontmatter` + +Accede directamente a los datos [frontmatter](../guide/frontmatter) de la página actual en expresiones Vue. + +```md +--- +title: Olá +--- + +# {{ $frontmatter.title }} +``` + +## `$params` + +Accede directamente a los [parámetros de ruta dinámica](../guide/routing#dynamic-routes) de la página actual en expresiones Vue. + +```md +- nombre del paquete: {{ $params.pkg }} +- versión: {{ $params.version }} +``` diff --git a/docs/es/reference/site-config.md b/docs/es/reference/site-config.md new file mode 100644 index 00000000..b2f3cf83 --- /dev/null +++ b/docs/es/reference/site-config.md @@ -0,0 +1,705 @@ +--- +outline: deep +--- + +# Configuración de site {#site-config} + +La configuración del site es donde puede configurar los ajustes globales del site. Las opciones de configuración de la aplicación definen las configuraciones que se aplican a todos los sites de VitePress, independientemente del tema que estén utilizando. Por ejemplo, el directorio base o el título del site. + +## Vista general {#overview} + +### Resolución de configuración {#config-resolution} + +El archivo de configuración siempre se resuelve desde `/.vitepress/config.[ext]`, donde `` es la [raiz del proyecto](../guide/routing#root-and-source-directory) VitePress y `[ext]` es una de las extensiones de archivo compatibles. TypeScript es compatible desde el primer momento. Las extensiones compatibles incluyen `.js`, `.ts`, `.mjs` y `.mts`. + +Recuerde usar la sintaxis de módulos ES en los archivos de configuración. El archivo de configuración debe exportar por defecto un objeto: + +```ts +export default { + // opciones de configuración a nivel de aplicación + lang: 'pt-BR', + title: 'VitePress', + description: 'Generador de site estático Vite & Vue.', + ... +} +``` + +:::details Configuración dinámica (Assíncrona) + +Si necesitas generar dinamicamente la configuración, también puedes exportar por defecto una función. Por ejemplo: + +```ts +import { defineConfig } from 'vitepress' + +export default async () => { + const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + + return defineConfig({ + // opciones de configuración a nivel de aplicación + lang: 'pt-BR', + title: 'VitePress', + description: 'Generador de site estático Vite & Vue.', + + // opciones de configuración a nivel de tema + themeConfig: { + sidebar: [ + ...posts.map((post) => ({ + text: post.name, + link: `/posts/${post.name}` + })) + ] + } + }) +} +``` + +También puedes utilizar `await` en el nivel superior. Como: + +```ts +import { defineConfig } from 'vitepress' + +const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + +export default defineConfig({ + // opciones de configuración a nivel de aplicación + lang: 'pt-BR', + title: 'VitePress', + description: 'Generador de site estático Vite & Vue.', + + // opciones de configuración a nivel de tema + themeConfig: { + sidebar: [ + ...posts.map((post) => ({ + text: post.name, + link: `/posts/${post.name}` + })) + ] + } +}) +``` + +::: + +### Configuración Intellisense {#config-intellisense} + +Usar el auxiliar `defineConfig` proporcionará Intellisense con tecnología TypeScript para las opciones de configuración. Suponiendo que su IDE lo admita, esto debería funcionar tanto en JavaScript como en TypeScript. + +```js +import { defineConfig } from 'vitepress' + +export default defineConfig({ + // ... +}) +``` + +### Configuración de Tema Escrito {#typed-theme-config} + +Por defecto, el auxiliar `defineConfig` espera el tipo de configuración del tema por defecto: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + // El tipo es `DefaultTheme.Config` + } +}) +``` + +Si usa un tema personalizado y desea realizar comprobaciones de tipo para la configuración del tema, deberá usar `defineConfigWithTheme` en su lugar, y pase el tipo de configuración para su tema personalizado a través de un argumento genérico: + +```ts +import { defineConfigWithTheme } from 'vitepress' +import type { ThemeConfig } from 'your-theme' + +export default defineConfigWithTheme({ + themeConfig: { + // El tipo es `ThemeConfig` + } +}) +``` + +### Configuración Vite, Vue & Markdown + +- **Vite** + + Puede configurar la instancia de Vite subyacente usando la opción [vite](#vite) en su configuración de VitePress. No es necesario crear un archivo de configuración de Vite por separado. + +- **Vue** + + VitePress ya incluye el plugin oficial de Vue para Vite ([@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue)). Puede configurar sus opciones usando la opción [vue](#vue) en su configuración VitePress. + +- **Markdown** + + Puede configurar la instancia subyacente de [Markdown-It](https://github.com/markdown-it/markdown-it) usando la opción [markdown](#markdown) en su configuración VitePress. + +## Metadatos de Site {#site-metadata} + +### title + +- Tipo: `string` +- Predeterminado: `VitePress` +- Puede ser reemplazado por página a través de [frontmatter](./frontmatter-config#title) + +Título de site. Al usar el tema por defecto, este será mostrado en la barra de navegación. + +También se utilizará como sufijo predeterminado para todos los títulos de páginas individuales a menos que [`titleTemplate`](#titletemplate) definirse. El título final de una página individual será el contenido textual de su primer encabezado. `

`, combinado con el título global como sufijo. Por ejemplo, con la siguiente configuración y contenido de página: + +```ts +export default { + title: 'Mi increible sitio web' +} +``` + +```md +# Hola +``` + +El título de la página será `Hola | Mi increible sitio web`. + +### titleTemplate + +- Tipo: `string | boolean` +- Puede ser reemplazado por página a través de [frontmatter](./frontmatter-config#titletemplate) + +Le permite personalizar el sufijo del título de cada página o el título completo. Por ejemplo: + +```ts +export default { + title: 'Mi increible sitio web', + titleTemplate: 'Sufijo Personalizado' +} +``` + +```md +# Hola +``` + +El título de la página será `Hola | Sufijo Personalizado`. + +Para personalizar completamente cómo se debe representar el título, puedes usar el símbolo `:title` en `titleTemplate`: + +```ts +export default { + titleTemplate: ':title - Sufijo Personalizado' +} +``` + +Aqui, `:title` será reemplazado por el texto que se deduce del primer título `

` de la página. El título del ejemplo de la página anterior será `Hola - Sufijo Personalizado`. + +Una opción puede ser definida como `false` para desactivar sufijos del título. + +### description + +- Tipo: `string` +- Predeterminado: `Um site VitePress` +- Puede ser sustituído por página a través de [frontmatter](./frontmatter-config#descrição) + +Descripción del sitio web. Esto se presentará como una etiqueta. `` en la página HTML. + +```ts +export default { + descripción: 'Un site VitePress' +} +``` + +### head + +- Tipo: `HeadConfig[]` +- Predeterminado: `[]` +- Se puede agregar por página a través de [frontmatter](./frontmatter-config#head) + +Elementos adicionales para agregar a la etiqueta `` de la página HTML. Las etiquetas agregadas por los usuarios son mostradas antes de la etiqueta `head` de cierre, despues de las etiquetas VitePress. + +```ts +type HeadConfig = + | [string, Record] + | [string, Record, string] +``` + +#### Ejemplo: Agregando un favicon {#example-adding-a-favicon} + +```ts +export default { + cabecera: [['link', { rel: 'icon', href: '/favicon.ico' }]] +} // coloque favicon.ico en el directorio público, si la base está definida, use /base/favicon.ico + +/* Mostraría: + +*/ +``` + +#### Ejemplo: Agregando Fuentes de Google {#example-adding-google-fonts} + +```ts +export default { + head: [ + [ + 'link', + { rel: 'preconnect', href: 'https://fonts.googleapis.com' } + ], + [ + 'link', + { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' } + ], + [ + 'link', + { href: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap', rel: 'stylesheet' } + ] + ] +} + +/* Mostraría: + + + +*/ +``` + +#### Ejemplo: Registrando un _service worker_ {#example-registering-a-service-worker} + +```ts +export default { + head: [ + [ + 'script', + { id: 'register-sw' }, + `;(() => { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js') + } + })()` + ] + ] +} + +/* Mostraría: + +*/ +``` + +#### Ejemplo: Usando Google Analytics {#example-using-google-analytics} + +```ts +export default { + head: [ + [ + 'script', + { async: '', src: 'https://www.googletagmanager.com/gtag/js?id=TAG_ID' } + ], + [ + 'script', + {}, + `window.dataLayer = window.dataLayer || []; + function gtag(){dataLayer.push(arguments);} + gtag('js', new Date()); + gtag('config', 'TAG_ID');` + ] + ] +} + +/* Mostraría: + + +*/ +``` + +### lang + +- Tipo: `string` +- Predeterminado: `en-US` + +El atributo de idioma del sitio. Esto se mostrará como una etiqueta. `` en la página HTML. + +```ts +export default { + lang: 'en-US' +} +``` + +### base + +- Tipo: `string` +- Predeterminado: `/` + +La URL base donde se implementará el sitio. Deberá configurar esto si planea implementar su sitio en un subdirectorio, por ejemplo, en páginas de GitHub. Si planea implementar su sitio web en `https://foo.github.io/bar/` entonces deberías definir la base como `'/bar/'`. Siempre debe comenzar y terminar con una barra. + +La base se agrega automáticamente a todas las URL que comienzan con / en otras opciones, por lo que solo necesitas especificarla una vez. + +```ts +export default { + base: '/base/' +} +``` + +## Roteamento {#routing} + +### cleanUrls + +- Tipo: `boolean` +- Predeterminado: `false` + +Cuando se establece en `true`, VitePress eliminará el `.html` al final de las URLs. Consulte también [Generar URL Limpia](../guide/routing#generating-clean-url). + +::: Alerta de Soporte de Servidor Requerido +Habilitar esto puede requerir configurar adicional en su plataforma de alojamiento. Para funcionar, su servidor debe poder servir `/foo.html` cuando visite `/foo` **sin redirección**. +::: + +### rewrites + +- Tipo: `Record` + +Define asignaciones de directorios personalizados <-> URL. Visite [Rutas: Reescribir Rutas](../guide/routing#route-rewrites) para obtener más detalles. + +```ts +export default { + rewrites: { + 'source/:page': 'destination/:page' + } +} +``` + +## Construcción {#build} + +### srcDir + +- Tipo: `string` +- Predeterminado: `.` + +El directorio donde se almacenan tus páginas de rebajas, en relación con la raíz del proyecto. vea también [Directorio Raiz y de origen](../guide/routing#root-and-source-directory). + +```ts +export default { + srcDir: './src' +} +``` + +### srcExclude + +- Tipo: `string` +- Predeterminado: `undefined` + +Un [patrón glob](https://github.com/mrmlnc/fast-glob#pattern-syntax) para hacer coincidir los archivos de rebajas que deben exluirse como contenido de origen. + +```ts +export default { + srcExclude: ['**/README.md', '**/TODO.md'] +} +``` + +### outDir + +- Tipo: `string` +- Predeterminado: `./.vitepress/dist` + +La ubicación de la salida de compilación para el sitio, en relación con el [raiz del proyecto](../guide/routing#root-and-source-directory). + +```ts +export default { + outDir: '../public' +} +``` + +### assetsDir + +- Tipo: `string` +- Predeterminado: `assets` + +Especifica el directorio para anidar los activos generados. El camino debe estar dentro [`outDir`](#outdir) y se resuelve en relación con el mismo. + +```ts +export default { + assetsDir: 'static' +} +``` + +### cacheDir + +- Tipo: `string` +- Predeterminado: `./.vitepress/cache` + +El directorio para los archivos de caché, en relación con el [raiz del proyecto](../guide/routing#root-and-source-directory). Vea también: [cacheDir](https://vitejs.dev/config/shared-options.html#cachedir). + +```ts +export default { + cacheDir: './.vitepress/.vite' +} +``` + +### ignoreDeadLinks + +- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- Predeterminado: `false` + +Cuando se establece en `true`, VitePress no dejará de compilarse debido a links rotos. + +Cuando se establece en `'localhostLinks'`, la compilación fallará en links rotos, per no verificará los links `localhost`. + +```ts +export default { + ignoreDeadLinks: true +} +``` + +También puede ser un _array_ de una exacta URL en string, patrones regex, o funciones de filtro personalizadas. + +```ts +export default { + ignoreDeadLinks: [ + // ignora URL exacta "/playground" + '/playground', + // ignora todos los links localhost + /^https?:\/\/localhost/, + // ignora todos los links incluyendo "/repl/"" + /\/repl\//, + // función personalizada, ignora todos los links incluyendo "ignore" + (url) => { + return url.toLowerCase().includes('ignore') + } + ] +} +``` + +### mpa + +- Tipo: `boolean` +- Predeterminado: `false` + +Cuando se define como `true`, la aplicación de producción se compilará en [Modo MPA](../guide/mpa-mode). El modo MPA envía 0 kb de JavaScript de forma predeterminada, a expensas de deshabilitar la navegación del lado del cliente y requerir permiso explícito para la interactividad. + +## Tematización {#theming} + +### appearance + +- Tipo: `boolean | 'dark' | 'force-dark' | import('@vueuse/core').UseDarkOptions` +- Predeterminado: `true` + +Se habilitará el modo oscuro (agregando una classe `.dark` al elemento ``). + +- Si la opción está configurada en `true` El tema predeterminado está determinado por la combinación de colores preferida del usuario. +- Si la opción está configurada en `dark` El tema es oscuro de forma predeterminada a menos que el usuario lo cambie manualmente. +- Si la opción está configurada en `false` los usuarios no podrán cambiar el tema. + +Esta opción inyecta un script en línea que restaura la configuración de los usuarios desde el almacenamiento local. (_local storage_) usando una llave `vitepress-theme-appearance`. Eso asegurará que la clase `.dark` se aplicará antes de que se muestre la página para evitar el parpadeo. + +`appearance.initialValue` puede ser `'dark' | undefined`. Refs o getters no son soportados. + +### lastUpdated + +- Tipo: `boolean` +- Predeterminado: `false` + +Para obtener la marca de tiempo de la última actualización para cada página usando Git. El sello de fecha se incluirá en los datos de cada página, accesible a través de [`useData`](./runtime-api#usedata). + +Cuando se utiliza el tema predeterminado, al habilitar esta opción se mostrará la última hora de actualización de cada página. Puedes personalizar el texto mediante la opción [`themeConfig.lastUpdatedText`](./default-theme-config#lastupdatedtext). + +## Personalización {#customization} + +### markdown + +- Tipo: `MarkdownOption` + +Configure las opciones de procesador Markdown. VitePress usa [Markdown-it](https://github.com/markdown-it/markdown-it) como procesador y [Shiki](https://github.com/shikijs/shiki) para resaltar la sintaxis del idioma. Dentro de esta opción, puede pasar varias opciones de Markdown relacionadas para satisfacer sus necesidades. + +```js +export default { + markdown: {...} +} +``` + +Consulte la [declaración de tipo y jsdocs](https://github.com/vuejs/vitepress/blob/main/src/node/markdown/markdown.ts) para conocer todas las opciones disponibles. + +### vite + +- Tipo: `import('vite').UserConfig` + +Pase la [Configuración Vite](https://vitejs.dev/config/) sin procesar al servidor interno / empaquetador Vite. + +```js +export default { + vite: { + // Opciones de configuración Vite + } +} +``` + +### vue + +- Tipo: `import('@vitejs/plugin-vue').Options` + +Pase las opciones [`@vitejs/plugin-vue`](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue#options) sin formato a la instancia del complemento interno. + +```js +export default { + vue: { + // Opciones @vitejs/plugin-vue + } +} +``` + +## Construir Ganchos {#build-hooks} + +Los enlaces de compilación VitePress permiten agregar nuevas funciones al su sitio web: + +- Sitemap +- Indexación de busqueda +- PWA +- _Teleports_ + +## buildEnd +- Tipo: `(siteConfig: SiteConfig) => Awaitable` +`buildEnd` es un enlace de compilación CLI (Interfaz de línea de comando), se ejecutará después de que se complete la compilación (SSG) pero antes de que finalice el proceso CLI de VitePress. + +```ts +export default { + async buildEnd(siteConfig) { + // ... + } +} +``` + +## postRender +- Tipo: `(context: SSGContext) => Awaitable` +- `postRender` es un gancho de compilación, llamado cuando se completa la interpretación de SSG. Le permitirá manipular el contenido de los _teleports_ durante la generación de sitios estáticos. + + ```ts + export default { + async postRender(context) { + // ... + } + } + ``` + + ```ts + interface SSGContext { + content: string + teleports?: Record + [key: string]: any + } + ``` + +## transformHead +- Tipo: `(context: TransformContext) => Awaitable` + +`transformHead` es un enlace de compilación para transformar el encabezado antes de generar cada página. Esto le permite agregar entradas de encabezado que no se pueden agregar estáticamente a la configuración de VitePress. Sólo necesita devolver entradas adicionales, que se fusionarán automáticamente con las existentes. + +:::warning +No mutes ningún elemento dentro `context`. +::: + +```ts +export default { + async transformHead(context) { + // ... + } +} +``` + +```ts +interface TransformContext { + page: string // e.g. index.md (relativo a srcDir) + assets: string[] // todos los activos no-js/css con URL pública completamente resuelta + siteConfig: SiteConfig + siteData: SiteData + pageData: PageData + title: string + description: string + head: HeadConfig[] + content: string +} +``` + +Tenga en cuenta que este enlace solo se llama cuando se genera el sitio de forma estática. No se llama durante el desarrollo. Si necesita agregar entradas de encabezado dinámicas durante el desarrollo, puede usar el enlace [`transformPageData`](#transformpagedata) en su lugar. + + ```ts + export default { + transformPageData(pageData) { + pageData.frontmatter.head ??= [] + pageData.frontmatter.head.push([ + 'meta', + { + name: 'og:title', + content: + pageData.frontmatter.layout === 'home' + ? `VitePress` + : `${pageData.title} | VitePress` + } + ]) + } + } + ``` + +#### Ejemplo: Agregando una URL canónica `` {#example-adding-a-canonical-url-link} + +```ts +export default { + transformPageData(pageData) { + const canonicalUrl = `https://example.com/${pageData.relativePath}` + .replace(/index\.md$/, '') + .replace(/\.md$/, '.html') + + pageData.frontmatter.head ??= [] + pageData.frontmatter.head.push([ + 'link', + { rel: 'canonical', href: canonicalUrl } + ]) + } +} +``` + +### transformHtml +- Tipo: `(code: string, id: string, context: TransformContext) => Awaitable` +`transformHtml` es un gancho de compilación para transformar el contenido de cada página antes de guardarla en el disco. + +:::warning +No mute ningún elemento dentro del `context`. Además, modificar el contenido HTML puede provocar problemas de hidratación en tiempo de ejecución. +::: + +```ts +export default { + async transformHtml(code, id, context) { + // ... + } +} +``` + +### transformPageData +- Tipo: `(pageData: PageData, context: TransformPageContext) => Awaitable | { [key: string]: any } | void>` + +`transformPageData` es un gancho para transformar los datos de cada página. Puedes hacer mutaciones directamente en `pageData` o devolver valores modificados que se fusionarán con los datos de la página. + +:::warning +No mute ningún elemento dentro del `context` y tenga cuidado ya que esto puede afectar el rendimiento del servidor de desarrollo, especialmente si tiene algunas solicitudes de red o cálculos pesados (como generar imágenes) en el gancho. Puede consultar `process.env.NODE_ENV === 'production'` para ver la lógica condicional. +::: + +```ts +export default { + async transformPageData(pageData, { siteConfig }) { + pageData.contributors = await getPageContributors(pageData.relativePath) + } + + // o devolver datos para fusionar + async transformPageData(pageData, { siteConfig }) { + return { + contributors: await getPageContributors(pageData.relativePath) + } + } +} +``` + +```ts +interface TransformPageContext { + siteConfig: SiteConfig +} +``` diff --git a/docs/ko/guide/asset-handling.md b/docs/ko/guide/asset-handling.md new file mode 100644 index 00000000..5f6a35d1 --- /dev/null +++ b/docs/ko/guide/asset-handling.md @@ -0,0 +1,63 @@ +# 에셋 핸들링 {#asset-handling} + +## 정적 에셋 참조하기 {#referencing-static-assets} + +모든 마크다운 파일은 Vue 컴포넌트로 컴파일되어 [Vite](https://vitejs.dev/guide/assets.html)에 의해 처리됩니다. 모든 에셋은 상대 URL을 사용하여 참조할 수 있으며, **참조해야 합니다**: + +```md +![이미지](./image.png) +``` + +마크다운 파일에서 정적 에셋을 참조할 수 있으며, 테마 내의 `*.vue` 컴포넌트, 스타일 및 일반 `.css` 파일을 절대 경로(프로젝트 루트를 기준으로) 또는 상대 경로(파일 시스템을 기준으로)를 사용하여 참조할 수 있습니다. 후자는 Vite, Vue CLI 또는 webpack의 `file-loader` 동작과 유사합니다. + +일반적인 이미지, 미디어 및 글꼴 파일 형식은 자동으로 에셋으로 감지되어 포함됩니다. + +::: tip 링크를 통해 참조된 파일은 에셋으로 처리되지 않습니다 +마크다운 파일 내에서 링크로 참조된 PDF 또는 기타 문서는 자동으로 에셋으로 처리되지 않습니다. 링크된 파일을 접근 가능하게 하려면 프로젝트의 [`public`](#the-public-directory) 디렉토리에 수동으로 배치해야 합니다. +::: + +절대 경로를 사용하는 에셋을 포함하여 모든 참조된 에셋은 프로덕션 빌드에서 해시된 파일 이름으로 출력 디렉토리에 복사됩니다. 참조되지 않은 에셋은 복사되지 않습니다. 4kb보다 작은 이미지 에셋은 base64로 인라인됩니다. 이는 [`vite`](../reference/site-config#vite) 구성 옵션을 통해 구성할 수 있습니다. + +모든 **정적** 경로 참조는 절대 경로를 포함하여 작업 디렉토리 구조를 기반으로 해야 합니다. + +## Public 디렉터리 {#the-public-directory} + +때때로 마크다운이나 테마 컴포넌트에서 직접 참조되지 않는 정적 에셋을 제공해야 하거나 특정 파일을 원래 파일 이름으로 제공하고 싶을 때가 있습니다. 이러한 파일의 예로는 `robots.txt`, 파비콘, PWA 아이콘 등이 있습니다. + +이 파일들은 [소스 디렉토리](./routing#source-directory) 아래의 `public` 디렉토리에 놓을 수 있습니다. 예를 들어 프로젝트 루트가 `./docs`이고 기본 소스 디렉토리 위치를 사용 중인 경우, `public` 디렉토리는 `./docs/public`이 됩니다. + +`public`에 배치된 에셋은 출력 디렉토리의 루트로 그대로 복사됩니다. + +`public`에 배치된 파일은 루트 절대 경로를 사용하여 참조해야 한다는 점에 유의하세요. 예를 들어, `public/icon.png`는 소스 코드에서 항상 `/icon.png`로 참조되어야 합니다. + +## Base URL {#base-url} + +사이트가 루트 URL이 아닌 곳에 배포된 경우, `.vitepress/config.js`에서 `base` 옵션을 설정해야 합니다. 예를 들어, 사이트를 `https://foo.github.io/bar/`에 배포하려는 경우 `base`는 `'/bar/'`로 설정해야 합니다(항상 슬래시로 시작하고 끝나야 합니다). + +모든 정적 에셋 경로는 다른 `base` 구성 값에 맞게 자동으로 처리됩니다. 예를 들어, 마크다운에서 `public` 하위의 에셋에 대한 절대 참조가 있는 경우: + +```md +![이미지](/image-inside-public.png) +``` + +이 경우 `base` 구성 값을 변경할 때 **업데이트할 필요가 없습니다**. + +그러나 테마 구성 값을 기반으로 `src`가 설정된 이미지와 같이 동적으로 에셋에 링크하는 테마 컴포넌트를 작성하는 경우: + +```vue + +``` + +이 경우 VitePress에서 제공하는 [`withBase` 헬퍼](../reference/runtime-api#withbase)로 경로를 감싸는 것이 좋습니다: + +```vue + + + +``` diff --git a/docs/ko/guide/cms.md b/docs/ko/guide/cms.md new file mode 100644 index 00000000..712c2402 --- /dev/null +++ b/docs/ko/guide/cms.md @@ -0,0 +1,56 @@ +--- +outline: deep +--- + +# CMS에 연결하기 {#connecting-to-a-cms} + +## 일반적인 워크플로우 {#general-workflow} + +VitePress를 CMS에 연결하는 것은 주로 [동적 라우트](./routing#dynamic-routes)를 중심으로 이루어질 것입니다. 진행하기 전에 작동 방식을 이해해야 합니다. + +각 CMS가 다르게 작동하므로, 여기서는 특정 상황에 맞게 조정해야 하는 일반적인 워크플로우만 제공할 수 있습니다. + +1. CMS가 인증을 요구하는 경우, `.env` 파일을 생성하여 API 토큰을 저장하고 다음과 같이 로드하세요: + + ```js + // posts/[id].paths.js + import { loadEnv } from 'vitepress' + + const env = loadEnv('', process.cwd()) + ``` + +2. CMS에서 필요한 데이터를 가져와 적절한 경로 데이터로 형식을 지정하세요: + + ```js + export default { + async paths() { + // 필요한 경우 해당 CMS 클라이언트 라이브러리 사용 + const data = await (await fetch('https://my-cms-api', { + headers: { + // 필요한 경우 토큰을 사용 + } + })).json() + + return data.map(entry => { + return { + params: { id: entry.id, /* 제목, 저자, 날짜 등 */ }, + content: entry.content + } + }) + } + } + ``` + +3. 페이지의 컨텐츠를 렌더링하세요: + + ```md + # {{ $params.title }} + + - 작성자: {{ $params.author }}, 작성일: {{ $params.date }} + + + ``` + +## 통합 가이드 {#integration-guides} + +VitePress를 특정 CMS와 통합하는 방법에 대한 가이드를 작성한 경우 아래의 "이 페이지 편집 제안하기" 링크를 클릭하여 여기에 제출하세요! diff --git a/docs/ko/guide/custom-theme.md b/docs/ko/guide/custom-theme.md new file mode 100644 index 00000000..6b319b4e --- /dev/null +++ b/docs/ko/guide/custom-theme.md @@ -0,0 +1,222 @@ +# 커스텀 테마 사용하기 {#using-a-custom-theme} + +## 테마 사용법 {#theme-resolving} + +`.vitepress/theme/index.js` 또는 `.vitepress/theme/index.ts` 파일("테마 엔트리 파일")을 생성하여 커스텀 테마를 활성화할 수 있습니다: + +``` +. +├─ docs # 프로젝트 루트 +│ ├─ .vitepress +│ │ ├─ theme +│ │ │ └─ index.js # 테마 엔트리 +│ │ └─ config.js # 구성 파일 +│ └─ index.md +└─ package.json +``` + +VitePress는 테마 엔트리 파일이 존재를 감지하면 기본 테마 대신 커스텀 테마를 사용합니다. 아니면 [기본 테마 확장하기](./extending-default-theme)를 통해 이를 기반으로 고급 커스터마이징을 수행할 수 있습니다. + +## 테마 인터페이스 {#theme-interface} + +VitePress 커스텀 테마는 아래와 같은 인터페이스 객체로 정의됩니다: + +```ts +interface Theme { + /** + * 모든 페이지의 루트 레이아웃 컴포넌트 + * @required + */ + Layout: Component + /** + * Vue 애플리케이션 인스턴스 추가조작 (의역: "enhance → 추가조작") + * @optional + */ + enhanceApp?: (ctx: EnhanceAppContext) => Awaitable + /** + * 현재 `enhanceApp`를 호출하기 전, 다른 테마를 먼저 확장 + * @optional + */ + extends?: Theme +} + +interface EnhanceAppContext { + app: App // Vue 애플리케이션 인스턴스 + router: Router // VitePress 라우터 인스턴스 + siteData: Ref // 사이트 수준 메타데이터 +} +``` + +테마 엔트리 파일은 테마(Theme 객체)를 "export default" 해야 합니다: + +```js +// .vitepress/theme/index.js + +// 테마 엔트리에서 Vue 파일을 직접 "import" 할 수 있습니다. +// VitePress는 @vitejs/plugin-vue가 사전 구성되어 있습니다. +import Layout from './Layout.vue' + +export default { + Layout, + enhanceApp({ app, router, siteData }) { + // ... + } +} +``` + +"export default"는 커스텀 테마를 설정하는 유일한 방법이며, `Layout` 프로퍼티만 필수입니다. 따라서 기술적으로 VitePress 테마는 단일 Vue 컴포넌트처럼 간단할 수 있습니다. + +레이아웃 컴포넌트 내부에서는 일반적인 Vite + Vue 3 애플리케이션처럼 동작합니다. 또한 테마가 [SSR 호환](./ssr-compat)이 되어야 합니다. + +## 레이아웃 만들기 {#building-a-layout} + +가장 기본적인 레이아웃 컴포넌트는 [``](../reference/runtime-api#content) 컴포넌트가 포함되어야 합니다: + +```vue + + +``` + +위의 레이아웃은 각 페이지의 마크다운을 HTML로 렌더링합니다. 첫 번째로 개선 사항은 404 에러를 처리하는 것입니다: + +```vue{1-4,9-12} + + + +``` + +[`useData()`](../reference/runtime-api#usedata) 헬퍼는 다양한 레이아웃을 조건부로 렌더링하는 데 필요한 모든 런타임 데이터를 제공합니다. 접근할 수 있는 다른 데이터 중 하나는 현재 페이지의 전문(front-matter)입니다. 이를 활용하여 각 페이지에 맞게 레이아웃을 제어할 수 있습니다. 예를 들어 특정 페이지에서 홈 페이지 레이아웃을 사용하도록 지정할 수 있습니다: + +```md +--- +layout: home +--- +``` + +그리고 이를 처리하도록 테마를 조정할 수 있습니다: + +```vue{3,12-14} + + + +``` + +물론 레이아웃을 더 많은 컴포넌트로 나눌 수 있습니다: + +```vue{3-5,12-15} + + + +``` + +테마 컴포넌트에서 사용할 수 있는 모든 항목에 대해서는 [런타임 API 레퍼런스](../reference/runtime-api)를 참고하세요. 또한 [빌드할 때 데이터 로딩하기](./data-loading)를 활용하여 데이터 기반의 레이아웃을 생성할 수 있습니다. 예를 들어 현재 프로젝트의 모든 블로그 게시물을 나열하는 페이지를 만들 수 있습니다. + +## 사용자 정의 테마 배포하기 {#distributing-a-custom-theme} + +커스텀 테마를 배포하는 가장 쉬운 방법은 [GitHub 템플릿 리포지토리](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-template-repository)로 제공하는 것입니다. + +테마를 npm 패키지로 배포하려면 다음 단계를 따라야 합니다: + +1. 패키지 엔트리에서 테마 객체를 "export default" 합니다. + +2. 해당되는 경우, 테마 구성 타입 정의를 `ThemeConfig`로 "export" 합니다. + +3. 테마에서 VitePress 구성을 조정해야 하는 경우, 사용자가 확장할 수 있도록 패키지 하위 경로(예: `my-theme/config`)에 해당 구성을 "export" 합니다. + +4. 테마 구성 옵션을 문서화합니다 (구성 파일과 전문 둘 다). + +5. 테마를 사용하는 방법에 대한 명확한 지침을 제공합니다 (아래 참조). + +## 커스텀 테마 사용하기 {#consuming-a-custom-theme} + +외부 테마를 사용하려면, 커스텀 테마 엔트리에서 테마를 "import" 후 다시 "export"합니다: + +```js +// .vitepress/theme/index.js +import Theme from 'awesome-vitepress-theme' + +export default Theme +``` + +테마를 확장해야 하는 경우: + +```js +// .vitepress/theme/index.js +import Theme from 'awesome-vitepress-theme' + +export default { + extends: Theme, + enhanceApp(ctx) { + // ... + } +} +``` + +테마가 특별한 VitePress 구성을 요구하는 경우, 해당 구성을 (외부 커스텀 테마를 사용하는 자신의) 구성 파일에서도 확장해야 합니다: + +```ts +// .vitepress/config.ts +import baseConfig from 'awesome-vitepress-theme/config' + +export default { + // 필요한 경우 테마 기본 구성 확장 + extends: baseConfig +} +``` + +마지막으로 테마가 테마 구성에 대한 타입을 제공하는 경우: + +```ts +// .vitepress/config.ts +import baseConfig from 'awesome-vitepress-theme/config' +import { defineConfigWithTheme } from 'vitepress' +import type { ThemeConfig } from 'awesome-vitepress-theme' + +export default defineConfigWithTheme({ + extends: baseConfig, + themeConfig: { + // 타입은 `ThemeConfig`입니다. + } +}) +``` diff --git a/docs/ko/guide/data-loading.md b/docs/ko/guide/data-loading.md new file mode 100644 index 00000000..c95b57be --- /dev/null +++ b/docs/ko/guide/data-loading.md @@ -0,0 +1,249 @@ +# 빌드할 때 데이터 로딩하기 {#build-time-data-loading} + +VitePress는 페이지나 컴포넌트에서 임의의 데이터를 로드하고 이를 가져올 수 있는 **데이터 로더** 기능을 제공합니다. 데이터 로딩은 **빌드할 때에만** 실행되며, 결과적으로 생성된 데이터는 최종 JavaScript 번들에 JSON으로 직렬화됩니다. + +데이터 로더는 원격 데이터를 가져오거나 로컬 파일을 기반으로 메타데이터를 생성하는 데 사용할 수 있습니다. 예를 들어, 데이터 로더를 사용하여 모든 로컬 API 페이지를 파싱하고 모든 API 항목의 색인을 자동으로 생성할 수 있습니다. + +## 기본 사용법 {#basic-usage} + +데이터 로더 파일은 반드시 `.data.js` 또는 `.data.ts`로 끝나야 합니다. 이 파일은 `load()` 메서드를 가진 객체를 "export default" 해야 합니다: + +```js +// example.data.js +export default { + load() { + return { + hello: 'world' + } + } +} +``` + +로더 모듈은 Node.js에서만 평가되므로, 필요한 경우 Node API와 npm 종속성을 "import" 할 수 있습니다. + +그런 다음 `.md` 페이지와 `.vue` 컴포넌트에서 `data`라는 이름으로 "export" 한 데이터를 이 파일에서 "import" 할 수 있습니다: + +```vue + + +
{{ data }}
+``` + +출력: + +```json +{ + "hello": "world" +} +``` + +데이터 로더 자체가 `data`를 "export" 하지 않는다는 점에 주목하십시오. VitePress가 백그라운드에서 `load()` 메서드를 호출하고 결과를 암묵적으로 `data`라는 이름으로 "export" 하기 때문입니다. + +이 방법은 로더가 비동기적이어도 작동합니다: + +```js +export default { + async load() { + // 원격 데이터 가져오기 + return (await fetch('...')).json() + } +} +``` + +## 로컬 파일에서 데이터 가져오기 {#data-from-local-files} + +로컬 파일을 기반으로 데이터를 생성해야 할 때는 데이터 로더에서 `watch` 옵션을 사용해야 합니다. 이 옵션을 사용하면 이러한 파일에 변경이 있을 때 핫 업데이트를 트리거할 수 있습니다. + +`watch` 옵션은 또한 여러 파일을 매칭하는 [glob 패턴](https://github.com/mrmlnc/fast-glob#pattern-syntax)을 사용할 수 있어서 편리합니다. 패턴은 로더 파일 자체에 상대적일 수 있으며, `load()` 함수는 매칭된 파일을 절대 경로로 받게 됩니다. + +다음 예제는 CSV 파일을 로드하고 이를 [csv-parse](https://github.com/adaltas/node-csv/tree/master/packages/csv-parse/)를 사용하여 JSON으로 변환하는 방법을 보여줍니다. 이 파일은 빌드할 때에만 실행되므로 CSV 파서를 클라이언트로 전송하지 않습니다! + +```js +import fs from 'node:fs' +import { parse } from 'csv-parse/sync' + +export default { + watch: ['./data/*.csv'], + load(watchedFiles) { + // watchedFiles는 매칭된 파일의 절대 경로 배열 입니다. + // 테마 레이아웃에서 목록을 렌더링하는 데 사용할 수 있는 + // 블로그 포스트 메타데이터 배열을 생성합니다. + return watchedFiles.map((file) => { + return parse(fs.readFileSync(file, 'utf-8'), { + columns: true, + skip_empty_lines: true + }) + }) + } +} +``` + +## `createContentLoader` + +콘텐츠가 많은 사이트를 구축할 때, 종종 "아카이브" 또는 "인덱스" 페이지를 만들어야 합니다. 이 페이지는 콘텐츠 모음에 있는 모든 항목(예: 블로그 게시물, API 페이지)을 나열하는 페이지입니다. 데이터 로더 API를 직접 사용하여 이를 구현할 수 있지만, VitePress는 이러한 일반적인 사용 사례를 간소화하기 위해 `createContentLoader` 헬퍼를 제공합니다: + +```js +// posts.data.js +import { createContentLoader } from 'vitepress' + +export default createContentLoader('posts/*.md', /* options */) +``` + +이 헬퍼는 [소스 디렉터리](./routing#source-directory)를 기준으로 glob 패턴을 허용하고 데이터 로드 파일에서 "default export"로 사용할 수 있는 `{ watch, load }` 데이터 로더 객체를 반환합니다. 또한 파일 수정 타임스탬프를 기반으로 캐싱을 구현하여 개발 성능을 향상시킵니다. + +참고로 로더는 마크다운 파일에서만 작동하며, 매칭되는 마크다운이 아닌 파일은 건너뜁니다. + +로드된 데이터는 `ContentData[]` 타입의 배열입니다: + +```ts +interface ContentData { + // 페이지에 매핑된 URL입니다. 예: /posts/hello.html (base는 포함하지 않음) + // 수동으로 반복하거나 커스텀 `transform`을 사용하여 경로를 정규화. + url: string + // 페이지의 전문(front-matter) 데이터 + frontmatter: Record + + // 다음은 관련 옵션이 활성화된 경우에만 나타납니다. + // 아래에서 이에 대해 논의할 것입니다. + src: string | undefined + html: string | undefined + excerpt: string | undefined +} +``` + +기본적으로 `url`과 `frontmatter`만 제공됩니다. 이는 로드된 데이터가 클라이언트 번들에 JSON으로 인라인되기 때문에 크기에 주의해야 합니다. 다음은 데이터를 사용하여 최소한의 블로그 인덱스 페이지를 구축하는 예입니다: + +```vue + + + +``` + +### 옵션 {#options} + +기본 데이터가 모든 요구 사항에 충족하지 않을 수 있습니다. 옵션을 사용하여 데이터를 변환할 수 있습니다: + +```js +// posts.data.js +import { createContentLoader } from 'vitepress' + +export default createContentLoader('posts/*.md', { + includeSrc: true, // 원시 마크다운 소스를 포함할까요? + render: true, // 렌더링된 전체 페이지 HTML을 포함할까요? + excerpt: true, // 발췌문을 포함할까요? + transform(rawData) { + // 필요에 따라 원시 데이터를 매핑, 정렬 또는 필터링. + // 최종 결과를 클라이언트에 전달. + return rawData.sort((a, b) => { + return +new Date(b.frontmatter.date) - +new Date(a.frontmatter.date) + }).map((page) => { + page.src // 원시 마크다운 소스 + page.html // 렌더링된 전체 페이지 HTML + page.excerpt // 렌더링된 발췌문 HTML (첫 번째 `---` 위에 있는 내용) + return {/* ... */} + }) + } +}) +``` + +[Vue.js 블로그](https://github.com/vuejs/blog/blob/main/.vitepress/theme/posts.data.ts)에서 어떻게 사용되었는지 확인해보세요. + +`createContentLoader` API는 [빌드 훅](../reference/site-config#build-hooks) 내에서도 사용할 수 있습니다: + +```js +// .vitepress/config.js +export default { + async buildEnd() { + const posts = await createContentLoader('posts/*.md').load() + // 포스트 메타데이터를 기반으로 파일 생성하기, 예: RSS 피드 + // 게시물 메타데이터를 기반으로 파일 생성, 예: RSS 피드 + } +} +``` + +**타입** + +```ts +interface ContentOptions { + /** + * src를 포함할까요? + * @default false + */ + includeSrc?: boolean + + /** + * src를 HTML로 렌더링하고 데이터에 포함할까요? + * @default false + */ + render?: boolean + + /** + * `boolean` 타입인 경우, 발췌문을 파싱하고 포함할지 여부를 나타냅니다. (HTML로 렌더링됨) + * + * `function` 타입인 경우, 콘텐츠에서 발췌문을 추출하는 방법을 제어합니다. + * + * `string` 타입인 경우, 발췌문을 추출하는 데 사용할 커스텀 구분자를 정의합니다. + * `excerpt`가 `true`인 경우 기본 구분자는 `---`입니다. + * + * @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt + * @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt_separator + * + * @default false + */ + excerpt?: + | boolean + | ((file: { data: { [key: string]: any }; content: string; excerpt?: string }, options?: any) => void) + | string + + /** + * 데이터를 변환합니다. 데이터는 컴포넌트나 마크다운 파일에서 가져올 경우, + * 클라이언트 번들에 JSON으로 포함됩니다. + */ + transform?: (data: ContentData[]) => T | Promise +} +``` + +## 데이터 로더의 "export" 타입 {#typed-data-loaders} + +TypeScript를 사용할 때, 로더와 `data` "export"를 다음과 같이 타입 지정할 수 있습니다: + +```ts +import { defineLoader } from 'vitepress' + +export interface Data { + // 데이터 타입 +} + +declare const data: Data +export { data } + +export default defineLoader({ + // type checked loader options + watch: ['...'], + async load(): Promise { + // ... + } +}) +``` + +## 구성 {#configuration} + +로더 내부에서 구성 정보를 가져오려면 다음과 같이 코드를 사용해야 합니다: + +```ts +import type { SiteConfig } from 'vitepress' + +const config: SiteConfig = (globalThis as any).VITEPRESS_CONFIG +``` diff --git a/docs/ko/guide/deploy.md b/docs/ko/guide/deploy.md new file mode 100644 index 00000000..5da3efa3 --- /dev/null +++ b/docs/ko/guide/deploy.md @@ -0,0 +1,336 @@ +--- +outline: deep +--- + +# VitePress 사이트 배포하기 {#deploy-your-vitepress-site} + +다음 가이드는 몇 가지 공통된 가정을 기반으로 합니다: + +- VitePress 사이트는 프로젝트의 `docs` 디렉토리 안에 있다. +- 기본 빌드 출력 디렉토리(`.vitepress/dist`)를 사용하고 있다. +- VitePress는 프로젝트의 로컬 종속성으로 설치되어 있으며, `package.json`에 다음 스크립트가 설정되어 있다: + + ```json + { + "scripts": { + "docs:build": "vitepress build docs", + "docs:preview": "vitepress preview docs" + } + } + ``` + +## 로컬에서 빌드하고 테스트하기 {#build-and-test-locally} + +1. 이 명령어를 실행하여 문서를 빌드합니다: + + ```sh + $ npm run docs:build + ``` + +2. 빌드가 완료되면, 다음 명령어를 실행하여 로컬에서 미리보기를 합니다: + + ```sh + $ npm run docs:preview + ``` + + `preview` 명령은 출력 디렉토리 `.vitepress/dist`를 `http://localhost:4173`에서 제공할 것입니다. 이를 사용하여 프로덕션에 푸시하기 전에 모든 것이 잘 보이는지 확인할 수 있습니다. + +3. `--port` 인자를 전달하여 서버의 포트를 구성할 수 있습니다. + + ```json + { + "scripts": { + "docs:preview": "vitepress preview docs --port 8080" + } + } + ``` + + 이제 `docs:preview` 메서드가 `http://localhost:8080`에서 서버를 시작합니다. + +## public 기본 경로 설정하기 {#setting-a-public-base-path} + +기본적으로 사이트가 도메인의 루트 경로(`/`)에 배포된다고 가정합니다. 예를 들어 사이트가 `https://mywebsite.com/blog/` 와 같은 서브 경로에서 제공될 경우, VitePress 구성에서 [`base`](../reference/site-config#base) 옵션을 `'/blog/'`로 설정해야 합니다. + +**예**: Github(또는 GitLab) Pages를 사용하여 `user.github.io/repo/`에 배포하는 경우, `base`를 `/repo/`로 설정하세요. + +## HTTP 캐시 헤더 {#http-cache-headers} + +프로덕션 서버에서 HTTP 헤더를 제어할 수 있다면, 반복 방문 시 더 나은 성능을 위해 `cache-control` 헤더를 구성할 수 있습니다. + +프로덕션 빌드는 정적 자산(JavaScript, CSS, `public`가 아닌 곳에서 가져온 에셋)에 대해 해시된 파일 이름을 사용합니다. 브라우저 개발 도구의 네트워크 탭을 사용하여 프로덕션 미리보기를 검사하면 `app.4f283b18.js`와 같은 파일을 볼 수 있습니다. + +이 `4f283b18` 해시는 파일의 내용에서 생성됩니다. 동일한 해시된 URL은 동일한 파일 내용을 제공할 것이 보장되며, 내용이 변경되면 URL도 변경됩니다. 이는 이러한 파일에 대해 가장 강력한 캐시 헤더를 안전하게 사용할 수 있음을 의미합니다. 모든 이러한 파일은 출력 디렉토리의 `assets/` 아래에 배치되므로, 다음 헤더를 구성할 수 있습니다: + +``` +Cache-Control: max-age=31536000,immutable +``` + +::: details Netlify `_headers` 파일 예시 + +``` +/assets/* + cache-control: max-age=31536000 + cache-control: immutable +``` + +참고: `_headers` 파일은 [public 디렉토리](./asset-handling#the-public-directory)에 배치해야 합니다. 이 경우 `docs/public/_headers`에 위치하여 출력 디렉토리에 그대로 복사됩니다. + +[Netlify 커스텀 헤더 문서](https://docs.netlify.com/routing/headers/) + +::: + +::: details Vercel 내의 `vercel.json` 구성 예시 + +```json +{ + "headers": [ + { + "source": "/assets/(.*)", + "headers": [ + { + "key": "Cache-Control", + "value": "max-age=31536000, immutable" + } + ] + } + ] +} +``` + +참고: `vercel.json` 파일은 **리포지토리**의 루트에 배치해야 합니다. + +[Vercel 헤더 구성에 대한 문서](https://vercel.com/docs/concepts/projects/project-configuration#headers) + +::: + +## 플랫폼 가이드 {#platform-guides} + +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render + +새 프로젝트를 설정하고 대시보드를 사용하여 다음 설정을 변경하세요: + +- **빌드 명령어:** `npm run docs:build` +- **출력 디렉토리:** `docs/.vitepress/dist` +- **노드 버전:** `18` (또는 그 이상) + +::: warning +HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 Vue에 의미가 있는 주석을 출력에서 제거할 것입니다. 제거되면 하이드레이션 불일치 오류가 발생할 수 있습니다. +::: + +### GitHub Pages + +1. 프로젝트의 `.github/workflows` 디렉토리 안에 `deploy.yml`이라는 파일을 만들고 다음과 같은 내용을 추가하세요: + + ```yaml + # VitePress 사이트를 GitHub Pages에 빌드하고 배포하는 샘플 워크플로우 + # + name: VitePress 사이트를 Pages에 배포 + + on: + # `main` 브랜치를 대상으로 하는 푸시에서 실행됩니다. 기본 브랜치로 `master`를 사용하는 경우 여기를 `master`로 변경하세요. + push: + branches: [main] + + # Actions 탭에서 이 워크플로우를 수동으로 실행할 수 있게 합니다. + workflow_dispatch: + + # GitHub Pages에 배포할 수 있도록 GITHUB_TOKEN의 권한을 설정합니다. + permissions: + contents: read + pages: write + id-token: write + + # 진행 중인 실행과 마지막으로 대기 중인 실행 사이에 대기 중인 실행을 건너뛰어 하나의 동시 배포만 허용합니다. + # 그러나 이러한 프로덕션 배포가 완료되도록 진행 중인 실행은 취소하지 않습니다. + concurrency: + group: pages + cancel-in-progress: false + + jobs: + # 빌드 작업 + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 # lastUpdated가 활성화되지 않은 경우 필요하지 않음 + # - uses: pnpm/action-setup@v3 # pnpm을 사용하는 경우 주석 해제 + # - uses: oven-sh/setup-bun@v1 # Bun을 사용하는 경우 주석 해제 + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm # 또는 pnpm / yarn + - name: Setup Pages + uses: actions/configure-pages@v4 + - name: Install dependencies + run: npm ci # 또는 pnpm install / yarn install / bun install + - name: Build with VitePress + run: npm run docs:build # 또는 pnpm docs:build / yarn docs:build / bun run docs:build + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: docs/.vitepress/dist + + # 배포 작업 + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + needs: build + runs-on: ubuntu-latest + name: Deploy + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + ``` + + ::: warning + VitePress의 `base` 옵션이 제대로 구성되어 있는지 확인하세요. 자세한 내용은 [public 기본 경로 설정하기](#setting-a-public-base-path)를 참고하세요. + ::: + +2. 리포지토리 설정의 "Pages" 메뉴 항목에서 "Build and deployment > Source"에서 "GitHub Actions"를 선택하세요. + +3. 변경 사항을 `main` 브랜치에 푸시하고 GitHub Actions 워크플로우가 완료될 때까지 기다립니다. 설정에 따라 사이트가 `https://.github.io/[repository]/` 또는 `https:///`에 배포된 것을 볼 수 있습니다. 사이트는 `main` 브랜치에 푸시할 때마다 자동으로 배포됩니다. + +### GitLab Pages + +1. VitePress 구성에서 `outDir`을 `../public`으로 설정하세요. `https://.gitlab.io//`에 배포하려면 `base` 옵션을 `'//'`로 구성하세요. 커스텀 도메인, 유저 또는 그룹 페이지에 배포하거나 GitLab에서 "Use unique domain" 설정이 활성화된 경우에는 `base`가 필요하지 않습니다. + +2. 변경 사항을 적용할 때마다 사이트를 빌드하고 배포하도록 하기 위해 프로젝트의 루트에 다음 내용을 가진 `.gitlab-ci.yml` 파일을 생성하세요: + + ```yaml + image: node:18 + pages: + cache: + paths: + - node_modules/ + script: + # - apk add git # alpine 과 같은 작은 도커 이미지를 사용하고 있고 lastUpdated 가 활성화된 경우 주석 처리를 제거하세요. + - npm install + - npm run docs:build + artifacts: + paths: + - public + only: + - main + ``` + +### Azure 정적 Web 앱 {#azure-static-web-apps} + +1. [공식 문서](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration)를 따르세요. + +2. 구성 파일에 다음 값을 설정하세요(필요하지 않은 값들, 예를 들어 `api_location` 같은 것은 제거하세요): + + - **`app_location`**: `/` + - **`output_location`**: `docs/.vitepress/dist` + - **`app_build_command`**: `npm run docs:build` + +### Firebase {#firebase} + +1. 프로젝트 루트에 `firebase.json`과 `.firebaserc`를 생성하세요: + + `firebase.json`: + + ```json + { + "hosting": { + "public": "docs/.vitepress/dist", + "ignore": [] + } + } + ``` + + `.firebaserc`: + + ```json + { + "projects": { + "default": "" + } + } + ``` + +2. `npm run docs:build`를 실행한 후, 배포하려면 이 명령어를 실행하세요: + + ```sh + firebase deploy + ``` + +### Surge + +1. `npm run docs:build`를 실행한 후, 배포하기 위해 이 명령어를 실행하세요: + + ```sh + npx surge docs/.vitepress/dist + ``` + +### Heroku + +1. [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static)에 제공된 문서와 가이드를 따르세요. + +2. 프로젝트 루트에 아래 내용을 포함한 `static.json` 파일을 생성하세요: + + ```json + { + "root": "docs/.vitepress/dist" + } + ``` + +### Edgio + +[Edgio에 VitePress 앱 생성 및 배포하기](https://docs.edg.io/guides/vitepress)를 참고하세요. + +### Kinsta 정적 사이트 호스팅 {#kinsta-static-site-hosting} + +[VitePress](https://kinsta.com/static-site-hosting/) 웹사이트를 [Kinsta](https://kinsta.com/static-site-hosting/)에 배포하려면 이 [지침](https://kinsta.com/docs/vitepress-static-site-example/)을 따르세요. + +### Stormkit + +[VitePress](https://stormkit.io) 프로젝트를 [Stormkit](https://www.stormkit.io)에 배포하려면 이 [지침](https://stormkit.io/blog/how-to-deploy-vitepress)을 따르세요. + +### Nginx + +다음은 Nginx 서버 블록 구성의 예입니다. 이 설정은 일반적인 텍스트 기반 에셋에 대한 gzip 압축, VitePress 사이트의 정적 파일을 적절한 캐싱 헤더와 함께 제공하는 규칙 및 `cleanUrls: true`를 처리하는 규칙을 포함합니다. + +```nginx +server { + gzip on; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; + + listen 80; + server_name _; + index index.html; + + location / { + # 콘텐츠 위치 + root /app; + + # 정확히 일치하는 파일 -> 정제된 URL로 역방향 매핑 -> 폴더 -> 파일 없음 + try_files $uri $uri.html $uri/ =404; + + # 존재하지 않는 페이지 + error_page 404 /404.html; + + # index.html이 없는 폴더는 이 설정에서 403 오류를 발생시킴 + error_page 403 /404.html; + + # 캐싱 헤더 조정 + # assets 폴더의 파일들은 해시된 파일명 사용 + location ~* ^/assets/ { + expires 1y; + add_header Cache-Control "public, immutable"; + } + } +} +``` + +이 구성은 빌드된 VitePress 사이트가 서버의 `/app` 디렉토리에 위치한다고 가정합니다. 사이트 파일이 다른 곳에 위치한 경우 `root` 지시문을 적절하게 조정하세요. + +::: warning index.html을 기본값으로 설정하지 마세요. +try_files는 다른 Vue 애플리케이션처럼 index.html을 기본값으로 할 수 없습니다. 이는 페이지 상태가 유효하지 않게 만듭니다. +::: + +추가 정보는 [공식 nginx 문서](https://nginx.org/en/docs/), 이슈 [#2837](https://github.com/vuejs/vitepress/discussions/2837), [#3235](https://github.com/vuejs/vitepress/issues/3235) 및 Mehdi Merah의 [블로그 포스트](https://blog.mehdi.cc/articles/vitepress-cleanurls-on-nginx-environment#readings)에서 확인할 수 있습니다. diff --git a/docs/ko/guide/extending-default-theme.md b/docs/ko/guide/extending-default-theme.md new file mode 100644 index 00000000..a6a8d380 --- /dev/null +++ b/docs/ko/guide/extending-default-theme.md @@ -0,0 +1,341 @@ +--- +outline: deep +--- + +# 기본 테마 확장하기 {#extending-the-default-theme} + +VitePress의 기본 테마는 문서화에 최적화되어 있으며, 커스텀할 수 있습니다. 포괄적인 옵션 목록은 [기본 테마 구성](../reference/default-theme-config)을 참고하세요. + +그러나 구성만으로는 충분하지 않을 수 있습니다. 예를 들어: + +1. CSS 스타일링을 조정해야 하는 경우. +2. 전역 컴포넌트를 등록하기 위해 Vue 애플리케이션 인스턴스를 수정해야 하는 경우. +3. 레이아웃 슬롯을 통해 테마에 커스텀 컨텐츠를 삽입해야 하는 경우. + +이러한 고급 커스터마이징은 기본 테마를 "확장"하는 커스텀 테마 사용이 필요 합니다. + +::: tip +진행하기 전에, 커스텀 테마가 어떻게 작동하는지 이해하려면 먼저 [커스텀 테마 사용하기](./custom-theme)를 읽어보세요. +::: + +## CSS 커스터마이징하기 {#customizing-css} + +기본 테마의 CSS는 루트 레벨의 CSS 변수를 재정의하여 커스터마이징 할 수 있습니다: + +```js +// .vitepress/theme/index.js +import DefaultTheme from 'vitepress/theme' +import './custom.css' + +export default DefaultTheme +``` + +```css +/* .vitepress/theme/custom.css */ +:root { + --vp-c-brand-1: #646cff; + --vp-c-brand-2: #747bff; +} +``` + +재정의할 수 있는 기본 테마 CSS 변수는 [여기](https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css)를 참고하세요. + +## 다른 폰트 사용하기 {#using-different-fonts} + +VitePress는 기본 폰트로 [Inter](https://rsms.me/inter/)를 사용하며, 빌드 결과물에 폰트를 포함시킵니다. 폰트는 프로덕션 환경에서 자동으로 미리 로드되지만, 다른 메인 폰트를 사용하고자 할 경우 이는 바람직하지 않을 수 있습니다. + +빌드 결과물에 Inter를 포함시키지 않으려면, `vitepress/theme-without-fonts`에서 테마를 "import" 합니다: + +```js +// .vitepress/theme/index.js +import DefaultTheme from 'vitepress/theme-without-fonts' +import './my-fonts.css' + +export default DefaultTheme +``` + +```css +/* .vitepress/theme/custom.css */ +:root { + --vp-font-family-base: /* 일반 텍스트 폰트 */ + --vp-font-family-mono: /* 코드 폰트 */ +} +``` + +::: warning +선택적 컴포넌트인 [팀 페이지](../reference/default-theme-team-page) 등을 사용하는 경우, 반드시 이들도 `vitepress/theme-without-fonts`에서 "import" 해야 합니다! +::: + +폰트가 `@font-face`를 통해 참조된 로컬 파일인 경우, 에셋으로 처리되어 해시된 파일 이름으로 `.vitepress/dist/assets`에 포함됩니다. 이 파일을 미리 로드하려면 [transformHead](../reference/site-config#transformhead) 빌드 훅을 사용해야 합니다: + +```js +// .vitepress/config.js +export default { + transformHead({ assets }) { + // 폰트를 매칭하기 위해 정규식을 적절히 조정하세요 + const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + if (myFontFile) { + return [ + [ + 'link', + { + rel: 'preload', + href: myFontFile, + as: 'font', + type: 'font/woff2', + crossorigin: '' + } + ] + ] + } + } +} +``` + +## 전역 컴포넌트 등록하기 {#registering-global-components} + +```js +// .vitepress/theme/index.js +import DefaultTheme from 'vitepress/theme' + +/** @type {import('vitepress').Theme} */ +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + // 커스텀 전역 컴포넌트 등록 + app.component('MyGlobalComponent' /* ... */) + } +} +``` + +TypeScript를 사용하는 경우: +```ts +// .vitepress/theme/index.ts +import type { Theme } from 'vitepress' +import DefaultTheme from 'vitepress/theme' + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + // 커스텀 전역 컴포넌트 등록 + app.component('MyGlobalComponent' /* ... */) + } +} satisfies Theme +``` + +Vite를 사용하므로, Vite의 [glob import 기능](https://vitejs.dev/guide/features.html#glob-import)을 활용하여 컴포넌트 디렉터리를 자동으로 등록할 수 있습니다. + +## 레이아웃 슬롯 {#layout-slots} + +기본 테마의 `` 컴포넌트는 페이지의 특정 위치에 컨텐츠를 삽입할 수 있는 몇 가지 슬롯을 가지고 있습니다. 다음은 아웃라인 앞에 컴포넌트를 삽입하는 예제입니다: + +```js +// .vitepress/theme/index.js +import DefaultTheme from 'vitepress/theme' +import MyLayout from './MyLayout.vue' + +export default { + extends: DefaultTheme, + // 슬롯을 삽입하는 래퍼 컴포넌트로 + // Layout을 재정의합니다 + Layout: MyLayout +} +``` + +```vue + + + + +``` + +또는 렌더 함수를 사용할 수도 있습니다. + +```js +// .vitepress/theme/index.js +import { h } from 'vue' +import DefaultTheme from 'vitepress/theme' +import MyComponent from './MyComponent.vue' + +export default { + extends: DefaultTheme, + Layout() { + return h(DefaultTheme.Layout, null, { + 'aside-outline-before': () => h(MyComponent) + }) + } +} +``` + +기본 테마 레이아웃에서 사용할 수 있는 슬롯의 전체 목록: + +- 전문(front-matter)으로 `layout: 'doc'` (기본값)이 활성화된 경우: + - `doc-top` + - `doc-bottom` + - `doc-footer-before` + - `doc-before` + - `doc-after` + - `sidebar-nav-before` + - `sidebar-nav-after` + - `aside-top` + - `aside-bottom` + - `aside-outline-before` + - `aside-outline-after` + - `aside-ads-before` + - `aside-ads-after` +- 전문으로 `layout: 'home'`이 활성화된 경우: + - `home-hero-before` + - `home-hero-info-before` + - `home-hero-info` + - `home-hero-info-after` + - `home-hero-actions-after` + - `home-hero-image` + - `home-hero-after` + - `home-features-before` + - `home-features-after` +- 전문으로 `layout: 'page'`이 활성화된 경우: + - `page-top` + - `page-bottom` +- 페이지를 찾을 수 없음(404)일 때: + - `not-found` +- 항상: + - `layout-top` + - `layout-bottom` + - `nav-bar-title-before` + - `nav-bar-title-after` + - `nav-bar-content-before` + - `nav-bar-content-after` + - `nav-screen-content-before` + - `nav-screen-content-after` + +## 뷰 트랜지션 API 사용하기 {#using-view-transitions-api} + +### 외형 토글 {#on-appearance-toggle} + +기본 테마를 확장하여 컬러 모드가 전환될 때 커스텀 트랜지션 효과를 제공할 수 있습니다. 예제: + +```vue + + + + + + + +``` + +결과 (**광과민성 주의!**: 색상 깜빡임, 갑작스러운 움직임, 밝은 빛): + +
+데모 + +![외형 토글 트랜지션 데모](/appearance-toggle-transition.webp) + +
+ +뷰 트랜지션에 대한 자세한 정보는 [크롬 문서](https://developer.chrome.com/docs/web-platform/view-transitions/)를 참고하세요. + +### 라우트 변경 시 {#on-route-change} + +곧 제공될 예정입니다. + +## 내부 컴포넌트 재정의하기 {#overriding-internal-components} + +Vite의 [별칭](https://vitejs.dev/config/shared-options.html#resolve-alias)을 사용하여 기본 테마 컴포넌트를 커스텀 컴포넌트로 대체할 수 있습니다: + +```ts +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vitepress' + +export default defineConfig({ + vite: { + resolve: { + alias: [ + { + find: /^.*\/VPNavBar\.vue$/, + replacement: fileURLToPath( + new URL('./components/CustomNavBar.vue', import.meta.url) + ) + } + ] + } + } +}) +``` + +컴포넌트의 정확한 이름을 알고 싶다면 [Vitepress 소스 코드](https://github.com/vuejs/vitepress/tree/main/src/client/theme-default/components)를 참고하세요. 컴포넌트는 내부적으로 사용되기 때문에, 마이너 릴리즈 사이에 이름이 변경될 가능성이 있습니다. diff --git a/docs/ko/guide/frontmatter.md b/docs/ko/guide/frontmatter.md new file mode 100644 index 00000000..09b1a2cd --- /dev/null +++ b/docs/ko/guide/frontmatter.md @@ -0,0 +1,48 @@ +# 전문 {#frontmatter} + +## 사용법 {#usage} + +VitePress는 모든 마크다운 파일에서 YAML 전문(frontmatter)을 지원하며, [gray-matter](https://github.com/jonschlinkert/gray-matter)로 이를 파싱합니다. 전문은 마크다운 파일의 맨 위에 있어야 하며(모든 엘리먼트 포함 ` + + +``` + +## RTL 지원 (실험적) {#rtl-support-experimental} + +RTL 지원을 위해, 구성 파일에 `dir: 'rtl'`을 지정하고 , 또는 와 같은 RTLCSS PostCSS 플러그인을 사용하세요. PostCSS 플러그인을 구성하여 CSS 명시성 문제를 방지하기 위해 `:where([dir="ltr"])` 및 `:where([dir="rtl"])`을 접두사로 사용해야 합니다. diff --git a/docs/ko/guide/markdown.md b/docs/ko/guide/markdown.md new file mode 100644 index 00000000..198063b3 --- /dev/null +++ b/docs/ko/guide/markdown.md @@ -0,0 +1,967 @@ +# 마크다운 확장 기능 {#markdown-extensions} + +VitePress는 내장된 마크다운 확장 기능을 제공합니다. + +## 헤더 앵커 {#header-anchors} + +헤더에는 자동으로 앵커 링크가 적용됩니다. 앵커 렌더링은 `markdown.anchor` 옵션을 사용하여 구성할 수 있습니다. + +### 커스텀 앵커 {#custom-anchors} + +자동 생성된 앵커 대신 커스텀 앵커 태그를 지정하려면 헤딩에 접미사를 추가하세요: + +``` +# Using custom anchors {#my-anchor} +``` + +이를 통해 기본값인 `#using-custom-anchors` 대신 `#my-anchor`로 헤딩에 링크할 수 있습니다. + +## 링크 {#links} + +내부 링크와 외부 링크 모두 특별하게 취급됩니다. + +### 내부 링크 {#internal-links} + +내부 링크는 SPA 탐색을 위한 라우터 링크로 변환됩니다. 또한 각 하위 디렉터리에 포함된 모든 `index.md`는 자동으로 `index.html`로 변환되며, 해당 URL은 `/`로 설정됩니다. + +예를 들어, 다음과 같은 디렉터리 구조가 주어진 경우: + +``` +. +├─ index.md +├─ foo +│ ├─ index.md +│ ├─ one.md +│ └─ two.md +└─ bar + ├─ index.md + ├─ three.md + └─ four.md +``` + +그리고 현재 `foo/one.md`에 있다고 가정하면: + +```md +[Home](/) +[foo](/foo/) +[foo heading](./#heading) +[bar - three](../bar/three) +[bar - three](../bar/three.md) +[bar - four](../bar/four.html) +``` + +### 페이지 접미사 {#page-suffix} + +페이지와 내부 링크는 기본적으로 `.html` 접미사와 함께 생성됩니다. + +### 외부 링크 {#external-links} + +외부 링크는 자동으로 `target="_blank" rel="noreferrer"`를 갖습니다. + +- [vuejs.org](https://vuejs.org) +- [VitePress on GitHub](https://github.com/vuejs/vitepress) + +## 전문 {#frontmatter} + +[YAML 전문](https://jekyllrb.com/docs/front-matter/)이 기본적으로 지원됩니다: + +```yaml +--- +title: Blogging Like a Hacker +lang: en-US +--- +``` + +이 데이터는 페이지의 나머지 부분과 모든 커스텀 및 테마 컴포넌트에서 사용할 수 있습니다. + +자세한 내용은 [전문](../reference/frontmatter-config)을 참고하세요. + +## GitHub 스타일 테이블 {#github-style-tables} + +**입력** + +```md +| Tables | Are | Cool | +| ------------- | :-----------: | ----: | +| col 3 is | right-aligned | $1600 | +| col 2 is | centered | $12 | +| zebra stripes | are neat | $1 | +``` + +**출력** + +| Tables | Are | Cool | +| ------------- | :-----------: | ----: | +| col 3 is | right-aligned | $1600 | +| col 2 is | centered | $12 | +| zebra stripes | are neat | $1 | + +## 이모지 :tada: {#emoji} + +**입력** + +``` +:tada: :100: +``` + +**출력** + +:tada: :100: + +[모든 이모지의 목록](https://github.com/markdown-it/markdown-it-emoji/blob/master/lib/data/full.mjs)이 제공됩니다. + +## 목차 {#table-of-contents} + +**입력** + +``` +[[toc]] +``` + +**출력** + +[[toc]] + +목차의 렌더링은 `markdown.toc` 옵션을 사용하여 구성할 수 있습니다. + +## 커스텀 컨테이너 {#custom-containers} + +커스텀 컨테이너는 타입, 제목, 콘텐츠를 정의할 수 있습니다. + +### 기본 제목 {#default-title} + +**입력** + +```md +::: info +정보 상자입니다. +::: + +::: tip +팁입니다. +::: + +::: warning +경고입니다. +::: + +::: danger +위험한 경고입니다. +::: + +::: details +세부 정보 블록입니다. +::: +``` + +**출력** + +::: info +정보 상자입니다. +::: + +::: tip +팁입니다. +::: + +::: warning +경고입니다. +::: + +::: danger +위험한 경고입니다. +::: + +::: details +세부 정보 블록입니다. +::: + +### 사용자 정의 제목 {#custom-title} + +컨테이너의 "타입" 바로 뒤에 텍스트를 추가하여 커스텀 제목을 설정할 수 있습니다. + +**입력** + +````md +::: danger 정지 +위험 지대, 진행하지 마세요 +::: + +::: details 코드를 보려면 클릭하세요 +```js +console.log('Hello, VitePress!') +``` +::: +```` + +**출력** + +::: danger 정지 +위험 지대, 진행하지 마세요 +::: + +::: details 코드를 보려면 클릭하세요 +```js +console.log('Hello, VitePress!') +``` +::: + +또는 사이트 구성에 다음을 추가하여 커스텀 제목을 전역적으로 설정할 수 있습니다. 이는 제목을 영어로 작성하지 않을 경우 유용합니다: + +```ts +// config.ts +export default defineConfig({ + // ... + markdown: { + container: { + tipLabel: '팁', + warningLabel: '경고', + dangerLabel: '위험', + infoLabel: '정보', + detailsLabel: '세부 정보' + } + } + // ... +}) +``` + +### `raw` + +이것은 VitePress와 스타일 및 라우터 충돌을 방지하기 위해 사용할 수 있는 특별한 컨테이너입니다. 컴포넌트 라이브러리를 문서화할 때 특히 유용합니다. 더 나은 분리를 위해 [whyframe](https://whyframe.dev/docs/integrations/vitepress)을 참고해 볼 수 있습니다. + +**문법** + +```md +::: raw +
로 감쌉니다 +::: +``` + +`vp-raw` 클래스는 엘리먼트에 직접 사용할 수도 있습니다. 스타일 분리는 현재 선택 사항입니다: + +- 선호하는 패키지 매니저를 사용하여 `postcss`를 설치하세요: + + ```sh + $ npm add -D postcss + ``` + +- `docs/postcss.config.mjs`라는 파일을 만들고 다음 내용을 추가하세요: + + ```js + import { postcssIsolateStyles } from 'vitepress' + + export default { + plugins: [postcssIsolateStyles()] + } + ``` + + 이것은 기본적으로 [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector)를 사용합니다. 다음과 같이 옵션을 전달할 수 있습니다: + + ```js + postcssIsolateStyles({ + includeFiles: [/vp-doc\.css/] // 기본값은 /base\.css/ + }) + ``` + +## GitHub 스타일 알림 {#github-flavored-alerts} + +VitePress는 [GitHub 스타일 알림](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts)을 콜아웃으로 렌더링하는 것을 지원합니다. 이것은 [커스텀 컨테이너](#custom-containers)와 같은 방식으로 렌더링됩니다. + +```md +> [!NOTE] +> 문서를 빠르게 탐색할 때에도 사용자가 놓치지 말아야 할 중요한 정보. + +> [!TIP] +> 사용자가 보다 원활하게 목표를 달성하는 데 도움이 되는 정보 + +> [!IMPORTANT] +> 사용자가 목표를 달성하는 데 중요한 정보. + +> [!WARNING] +> 위험 가능성 때문에 사용자의 즉각적인 주의가 필요한 중요한 정보. + +> [!CAUTION] +> 실행할 경우 잠재적으로 부정적인 결과를 생성한다는 것을 알리는 정보. +``` + +> [!NOTE] +> 문서를 빠르게 탐색할 때에도 사용자가 놓치지 말아야 할 중요한 정보. + +> [!TIP] +> 사용자가 보다 원활하게 목표를 달성하는 데 도움이 되는 정보 + +> [!IMPORTANT] +> 사용자가 목표를 달성하는 데 중요한 정보. + +> [!WARNING] +> 위험 가능성 때문에 사용자의 즉각적인 주의가 필요한 중요한 정보. + +> [!CAUTION] +> 실행할 경우 잠재적으로 부정적인 결과를 생성한다는 것을 알리는 정보. + +## 코드 블록 내 구문 강조 {#syntax-highlighting-in-code-blocks} + +VitePress는 마크다운 코드 블록 내 언어 문법을 색상이 있는 텍스트로 강조하기 위해 [Shiki](https://github.com/shikijs/shiki)를 사용합니다. Shiki는 다양한 프로그래밍 언어를 지원합니다. 코드 블록의 시작 백틱에 유효한 언어 별칭을 추가하기만 하면 됩니다: + +**입력** + +````markdown +```js +export default { + name: 'MyComponent', + // ... +} +``` +```` + +````markdown +```html +
    +
  • + {{ todo.text }} +
  • +
+``` +```` + +**출력** + +```js +export default { + name: 'MyComponent', + // ... +} +``` + +```html +
    +
  • + {{ todo.text }} +
  • +
+``` + +Shiki의 리포지터리에서 사용 가능한 [유효한 언어 목록](https://shiki.style/languages)이 제공됩니다. + +또한 애플리케이션 구성에서 구문 강조 테마를 커스텀 할 수 있습니다. 자세한 내용은 [`markdown` 옵션](../reference/site-config#markdown)을 참고하세요. + +## 코드 블록에서 라인 강조 {#line-highlighting-in-code-blocks} + +**입력** + +````markdown +```js{4} +export default { + data () { + return { + msg: '강조됨!' + } + } +} +``` +```` + +**출력** + +```js{4} +export default { + data() { + return { + msg: '강조됨!' + } + } +} +``` + +단일 라인 뿐만 아니라 여러 개의 단일 라인, 범위 또는 둘 다 지정할 수도 있습니다: + +- 라인 범위: `{5-8}`, `{3-10}`, `{10-17}` +- 여러 단일 라인: `{4,7,9}` +- 라인 범위와 단일 라인: `{4,7-13,16,23-27,40}` + +**입력** + +````markdown +```js{1,4,6-8} +export default { // 강조됨 + data () { + return { + msg: `강조됨! + 이 줄은 강조되지 않습니다, + 하지만 이 줄과 다음 2줄은 강조됩니다.`, + motd: 'VitePress는 멋져요', + lorem: 'ipsum' + } + } +} +``` +```` + +**출력** + +```js{1,4,6-8} +export default { // 강조됨 + data () { + return { + msg: `강조됨! + 이 줄은 강조되지 않습니다, + 하지만 이 줄과 다음 2줄은 강조됩니다.`, + motd: 'VitePress는 멋져요', + lorem: 'ipsum', + } + } +} +``` + +또는 `// [!code highlight]` 주석을 사용하여 직접 라인에 강조를 추가할 수 있습니다. + +**입력** + +````markdown +```js +export default { + data () { + return { + msg: '강조됨!' // [!!code highlight] + } + } +} +``` +```` + +**출력** + +```js +export default { + data () { + return { + msg: '강조됨!' // [!code highlight] + } + } +} +``` + +## 코드 블록에서 포커싱 {#focus-in-code-blocks} + +`// [!code focus]` 주석을 라인에 추가하면 해당 라인이 포커싱되고 코드의 다른 부분은 흐릿하게 처리됩니다. + +추가로 `// [!code focus:]`를 사용하여 포커싱할 라인 수를 정의할 수 있습니다. + +**입력** + +````markdown +```js +export default { + data () { + return { + msg: '포커싱됨!' // [!!code focus] + } + } +} +``` +```` + +**출력** + +```js +export default { + data () { + return { + msg: '포커싱됨!' // [!code focus] + } + } +} +``` + +## 코드 블록 내 차이점 색 강조 {#colored-diffs-in-code-blocks} + +`// [!code --]` 또는 `// [!code ++]` 주석을 라인에 추가하면 해당 라인의 차이점을 나타내며, 코드 블록의 색상을 유지합니다. + +**입력** + +````markdown +```js +export default { + data () { + return { + msg: '삭제됨' // [!!code --] + msg: '추가됨' // [!!code ++] + } + } +} +``` +```` + +**출력** + +```js +export default { + data () { + return { + msg: '삭제됨' // [!code --] + msg: '추가됨' // [!code ++] + } + } +} +``` + +## 코드 블록 내 오류 및 경고 {#errors-and-warnings-in-code-blocks} + +`// [!code warning]` 또는 `// [!code error]` 주석을 라인에 추가하면 해당 라인이 색칠됩니다. + +**입력** + +````markdown +```js +export default { + data () { + return { + msg: '오류', // [!!code error] + msg: '경고' // [!!code warning] + } + } +} +``` +```` + +**출력** + +```js +export default { + data () { + return { + msg: '오류', // [!code error] + msg: '경고' // [!code warning] + } + } +} +``` + +## 라인 번호 {#line-numbers} + +구성을 통해 각 코드 블록에 라인 번호를 활성화할 수 있습니다: + +```js +export default { + markdown: { + lineNumbers: true + } +} +``` + +자세한 내용은 [`markdown` 옵션](../reference/site-config#markdown)을 참고하세요. + +구성에서 지정한 값을 무시하려면 펜싱 코드 블록에 `:line-numbers` / `:no-line-numbers` 마크를 추가하면 됩니다. + +또한 `=`를 `:line-numbers` 뒤에 추가하여 시작 라인 번호를 커스텀 할 수도 있습니다. 예를 들어 `:line-numbers=2`는 코드 블록의 라인 번호가 `2`부터 시작함을 의미합니다. + +**입력** + +````md +```ts {1} +// 줄 번호는 기본적으로 비활성화되어 있음 +const line2 = 'This is line 2' +const line3 = 'This is line 3' +``` + +```ts:line-numbers {1} +// 줄 번호가 활성화됨 +const line2 = 'This is line 2' +const line3 = 'This is line 3' +``` + +```ts:line-numbers=2 {1} +// 줄 번호가 활성화되고 2부터 시작함 +const line3 = 'This is line 3' +const line4 = 'This is line 4' +``` +```` + +**출력** + +```ts {1} +// 줄 번호는 기본적으로 비활성화되어 있음 +const line2 = 'This is line 2' +const line3 = 'This is line 3' +``` + +```ts:line-numbers {1} +// 줄 번호가 활성화됨 +const line2 = 'This is line 2' +const line3 = 'This is line 3' +``` + +```ts:line-numbers=2 {1} +// 줄 번호가 활성화되고 2부터 시작함 +const line3 = 'This is line 3' +const line4 = 'This is line 4' +``` + +## 코드 스니펫 가져오기 {#import-code-snippets} + +다음 문법을 통해 기존 파일에서 코드 스니펫을 가져올 수 있습니다: + +```md +<<< @/파일경로 +``` + +다음과 같이 [라인 강조](#line-highlighting-in-code-blocks)도 지원합니다: + +```md +<<< @/파일경로{강조 할 라인} +``` + +**입력** + +```md +<<< @/snippets/snippet.js{2} +``` + +**코드 파일** + +<<< @/snippets/snippet.js + +**출력** + +<<< @/snippets/snippet.js{2} + +::: tip +`@`의 값은 소스 루트에 해당합니다. 기본값은 VitePress 프로젝트 루트이지만, `srcDir`이 구성되어 있을 경우에는 다릅니다. 상대 경로에서도 가져올 수도 있습니다: + +```md +<<< ../snippets/snippet.js +``` + +::: + +특정 부분의 코드 파일만 포함하려면 [VS Code 리전](https://code.visualstudio.com/docs/editor/codebasics#_folding)을 사용할 수 있습니다. 파일 경로 뒤에 `#`을 사용한 다음 커스텀 리전 이름을 제공할 수 있습니다: + +**입력** + +```md +<<< @/snippets/snippet-with-region.js#snippet{1} +``` + +**코드 파일** + +<<< @/snippets/snippet-with-region.js + +**출력** + +<<< @/snippets/snippet-with-region.js#snippet{1} + +괄호(`{}`) 안에 언어를 지정할 수도 있습니다: + +```md +<<< @/snippets/snippet.cs{c#} + + + +<<< @/snippets/snippet.cs{1,2,4-6 c#} + + + +<<< @/snippets/snippet.cs{1,2,4-6 c#:line-numbers} +``` + +이는 파일 확장명에서 소스 언어를 유추할 수 없을 때 유용합니다. + +## 코드 그룹 {#code-groups} + +다음과 같이 여러 코드 블록을 그룹화할 수 있습니다: + +**입력** + +````md +::: code-group + +```js [config.js] +/** + * @type {import('vitepress').UserConfig} + */ +const config = { + // ... +} + +export default config +``` + +```ts [config.ts] +import type { UserConfig } from 'vitepress' + +const config: UserConfig = { + // ... +} + +export default config +``` + +::: +```` + +**출력** + +::: code-group + +```js [config.js] +/** + * @type {import('vitepress').UserConfig} + */ +const config = { + // ... +} + +export default config +``` + +```ts [config.ts] +import type { UserConfig } from 'vitepress' + +const config: UserConfig = { + // ... +} + +export default config +``` + +::: + +코드 그룹에서 [스니펫 가져오기](#import-code-snippets)도 할 수 있습니다: + +**입력** + +```md +::: code-group + + + +<<< @/snippets/snippet.js + + + +<<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [지역 스니펫] + +::: +``` + +**출력** + +::: code-group + +<<< @/snippets/snippet.js + +<<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [지역 스니펫] + +::: + +## 마크다운 파일 포함 {#markdown-file-inclusion} + +마크다운 파일을 다른 마크다운 파일에 포함시킬 수 있으며, 중첩도 가능합니다. + +::: tip +마크다운 경로 앞에 `@`를 붙일 수도 있으며, 이는 소스 루트로 작동합니다. 기본적으로 이는 VitePress 프로젝트 루트이며, `srcDir`이 구성되지 않은 경우입니다. +::: + +다음과 같이 상대적인 마크다운 파일을 포함시킬 수 있습니다: + +**입력** + +```md +# Docs + +## Basics + + +``` + +**해당 파일** (`parts/basics.md`) + +```md +Some getting started stuff. + +### Configuration + +Can be created using `.foorc.json`. +``` + +**동일한 코드** + +```md +# Docs + +## Basics + +Some getting started stuff. + +### Configuration + +Can be created using `.foorc.json`. +``` + +라인 범위 선택도 지원합니다: + +**입력** + +```md +# Docs + +## Basics + + +``` + +**해당 파일** (`parts/basics.md`) + +```md +Some getting started stuff. + +### Configuration + +Can be created using `.foorc.json`. +``` + +**동일한 코드** + +```md +# Docs + +## Basics + +### Configuration + +Can be created using `.foorc.json`. +``` + +선택된 라인 범위의 형식은 `{3,}`, `{,10}`, `{1,10}`이 될 수 있습니다. + +[VS Code 리전](https://code.visualstudio.com/docs/editor/codebasics#_folding)을 사용하여 코드 파일의 해당 부분만 포함할 수도 있습니다. 파일 경로 뒤에 `#`를 붙이고 커스텀 영역 이름을 제공할 수 있습니다: + +**입력** + +```md +# Docs + +## Basics + + + +``` + +**해당 파일** (`parts/basics.md`) + +```md + +## Usage Line 1 + +## Usage Line 2 + +## Usage Line 3 + +``` + +**동일한 코드** + +```md +# Docs + +## Basics + +## Usage Line 1 + +## Usage Line 3 +``` + +::: warning +파일이 존재하지 않더라도 오류가 발생하지 않는다는 점에 유의하십시오. 따라서 이 기능을 사용할 때 내용이 예상대로 렌더링되고 있는지 확인해야 합니다. +::: + +## 수식 {#math-equations} + +선택 사항입니다. 활성화하려면 `markdown-it-mathjax3`를 설치하고 설정 파일에서 `markdown.math`를 `true`로 설정해야 합니다: + +```sh +npm add -D markdown-it-mathjax3 +``` + +```ts +// .vitepress/config.ts +export default { + markdown: { + math: true + } +} +``` + +**입력** + +```md +$a \ne 0$ 일 때, $(ax^2 + bx + c = 0)$의 두 해는 다음과 같습니다: +$$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ + +**맥스웰 방정식:** + +| 방정식 | 설명 | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| $\nabla \cdot \vec{\mathbf{B}} = 0$ | $\vec{\mathbf{B}}$의 발산은 0입니다 | +| $\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | $\vec{\mathbf{E}}$의 회전은 $\vec{\mathbf{B}}$의 시간에 따른 변화율에 비례합니다 | +| $\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _wha?_ | +``` + +**출력** + +$a \ne 0$ 일 때, $(ax^2 + bx + c = 0)$의 두 해는 다음과 같습니다: +$$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ + +**맥스웰 방정식:** + +| 방정식 | 설명 | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| $\nabla \cdot \vec{\mathbf{B}} = 0$ | $\vec{\mathbf{B}}$의 발산은 0입니다 | +| $\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | $\vec{\mathbf{E}}$의 회전은 $\vec{\mathbf{B}}$의 시간에 따른 변화율에 비례합니다 | +| $\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _wha?_ | + +## 이미지 지연 로딩 {#image-lazy-loading} + +마크다운을 통해 추가된 각 이미지에 대해 지연 로딩을 활성화하려면 구성 파일에서 `lazyLoading`을 `true`로 설정하세요: + +```js +export default { + markdown: { + image: { + // 이미지 지연 로딩은 기본적으로 비활성화 되어 있습니다 + lazyLoading: true + } + } +} +``` + +## 고급 설정 {#advanced-configuration} + +VitePress는 마크다운 렌더러로 [markdown-it](https://github.com/markdown-it/markdown-it)을 사용합니다. 위의 많은 확장 기능은 커스텀 플러그인을 통해 구현됩니다. `.vitepress/config.js`의 `markdown` 옵션을 사용하여 `markdown-it` 인스턴스를 추가로 커스터마이즈할 수 있습니다: + +```js +import { defineConfig } from 'vitepress' +import markdownItAnchor from 'markdown-it-anchor' +import markdownItFoo from 'markdown-it-foo' + +export default defineConfig({ + markdown: { + // markdown-it-anchor의 옵션 + // https://github.com/valeriangalliat/markdown-it-anchor#usage + anchor: { + permalink: markdownItAnchor.permalink.headerLink() + }, + + // @mdit-vue/plugin-toc의 옵션 + // https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc#options + toc: { level: [1, 2] }, + + config: (md) => { + // 더 많은 markdown-it 플러그인을 사용! + md.use(markdownItFoo) + } + } +}) +``` + +구성 가능한 프로퍼티의 전체 목록은 [레퍼런스: 앱 구성](../reference/site-config#markdown)에서 확인하세요. diff --git a/docs/ko/guide/migration-from-vitepress-0.md b/docs/ko/guide/migration-from-vitepress-0.md new file mode 100644 index 00000000..f3ba5293 --- /dev/null +++ b/docs/ko/guide/migration-from-vitepress-0.md @@ -0,0 +1,23 @@ +# Migration from VitePress 0.x {#migration-from-vitepress-0-x} + +If you're coming from VitePress 0.x version, there're several breaking changes due to new features and enhancement. Please follow this guide to see how to migrate your app over to the latest VitePress. + +## App Config {#app-config} + +- The internationalization feature is not yet implemented. + +## Theme Config {#theme-config} + +- `sidebar` option has changed its structure. + - `children` key is now named `items`. + - Top level item may not contain `link` at the moment. We're planning to bring it back. +- `repo`, `repoLabel`, `docsDir`, `docsBranch`, `editLinks`, `editLinkText` are removed in favor of more flexible api. + - For adding GitHub link with icon to the nav, use [Social Links](../reference/default-theme-nav#navigation-links) feature. + - For adding "Edit this page" feature, use [Edit Link](../reference/default-theme-edit-link) feature. +- `lastUpdated` option is now split into `config.lastUpdated` and `themeConfig.lastUpdatedText`. +- `carbonAds.carbon` is changed to `carbonAds.code`. + +## Frontmatter Config {#frontmatter-config} + +- `home: true` option has changed to `layout: home`. Also, many Homepage related settings have been modified to provide additional features. See [Home Page guide](../reference/default-theme-home-page) for details. +- `footer` option is moved to [`themeConfig.footer`](../reference/default-theme-config#footer). diff --git a/docs/ko/guide/migration-from-vuepress.md b/docs/ko/guide/migration-from-vuepress.md new file mode 100644 index 00000000..c554e260 --- /dev/null +++ b/docs/ko/guide/migration-from-vuepress.md @@ -0,0 +1,30 @@ +# Migration from VuePress {#migration-from-vuepress} + +## Config {#config} + +### Sidebar {#sidebar} + +The sidebar is no longer automatically populated from frontmatter. You can [read the frontmatter yourself](https://github.com/vuejs/vitepress/issues/572#issuecomment-1170116225) to dynamically populate the sidebar. [Additional utilities for this](https://github.com/vuejs/vitepress/issues/96) may be provided in the future. + +## Markdown {#markdown} + +### Images {#images} + +Unlike VuePress, VitePress handles [`base`](./asset-handling#base-url) of your config automatically when you use static image. + +Hence, now you can render images without `img` tag. + +```diff +- foo ++ ![foo](/foo.png) +``` + +::: warning +For dynamic images you still need `withBase` as shown in [Base URL guide](./asset-handling#base-url). +::: + +Use `` regex to find and replace it with `![$2]($1)` to replace all the images with `![](...)` syntax. + +--- + +more to follow... diff --git a/docs/ko/guide/mpa-mode.md b/docs/ko/guide/mpa-mode.md new file mode 100644 index 00000000..b3308738 --- /dev/null +++ b/docs/ko/guide/mpa-mode.md @@ -0,0 +1,23 @@ +# MPA 모드 {#mpa-mode} + +MPA (다중 페이지 애플리케이션) 모드는 명령줄에서 `vitepress build --mpa`를 통해 활성화할 수 있으며, 구성 파일에서 `mpa: true` 옵션을 통해서도 활성화할 수 있습니다. + +MPA 모드에서는 모든 페이지가 기본적으로 JavaScript 없이 렌더링됩니다. 그 결과, 프로덕션 사이트는 감사 도구로부터 초기 방문 성능 점수가 더 좋을 가능성이 있습니다. + +그러나 SPA 탐색이 없기 때문에 페이지 간 링크는 전체 페이지를 새로 고침합니다. MPA 모드에서의 포스트-로드 탐색은 SPA 모드만큼 즉각적으로 느껴지지 않을 것입니다. + +또한 기본적으로 JS가 없다는 것은 Vue를 순전히 서버 사이드 템플릿 언어로 사용하고 있다는 것을 의미합니다. 브라우저에서는 이벤트 핸들러가 첨부되지 않으므로 상호작용이 없습니다. 클라이언트 사이드 JavaScript를 로드하려면 특별한 ` + +# Hello +``` + +` +``` + +### 원시 콘텐츠 렌더링 {#rendering-raw-content} + +페이지에 전달되는 파라미터는 클라이언트 JavaScript 페이로드에서 직렬화되므로, 원격 CMS에서 가져온 원시 Markdown이나 HTML 콘텐츠와 같은 무거운 데이터를 파라미터로 전달하지 마십시오. + +대신, 각 경로 객체의 `content` 프로퍼티를 사용하여 이러한 콘텐츠를 각 페이지에 전달할 수 있습니다: + +```js +export default { + async paths() { + const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + + return posts.map((post) => { + return { + params: { id: post.id }, + content: post.content // 원시 마크다운 또는 HTML + } + }) + } +} +``` + +그런 다음 특수 문법을 사용하여 마크다운 파일 자체의 일부로 콘텐츠를 렌더링할 수 있습니다: + +```md + +``` diff --git a/docs/ko/guide/sitemap-generation.md b/docs/ko/guide/sitemap-generation.md new file mode 100644 index 00000000..54db8e8a --- /dev/null +++ b/docs/ko/guide/sitemap-generation.md @@ -0,0 +1,58 @@ +# 사이트맵 생성 {#sitemap-generation} + +VitePress는 사이트의 `sitemap.xml` 파일 생성을 지원합니다. 이를 활성화하려면 `.vitepress/config.js`에 다음을 추가하십시오: + +```ts +export default { + sitemap: { + hostname: 'https://example.com' + } +} +``` + +`` 태그를 `sitemap.xml`에 포함하려면 [`lastUpdated`](../reference/default-theme-last-updated) 옵션을 활성화할 수 있습니다. + +## 옵션 {#options} + +사이트맵 지원은 [`sitemap`](https://www.npmjs.com/package/sitemap) 모듈에 의해 제공됩니다. 구성 파일의 `sitemap` 옵션에 지원되는 모든 옵션을 전달할 수 있습니다. 이러한 옵션은 `SitemapStream` 생성자에 직접 전달됩니다. 자세한 내용은 [`sitemap` 문서](https://www.npmjs.com/package/sitemap#options-you-can-pass)를 참고하세요. 예: + +```ts +export default { + sitemap: { + hostname: 'https://example.com', + lastmodDateOnly: false + } +} +``` + +구성 파일에서 `base`를 사용하는 경우, `hostname` 옵션에 이것을 추가해야 합니다: + +```ts +export default { + base: '/my-site/', + sitemap: { + hostname: 'https://example.com/my-site/' + } +} +``` + +## `transformItems` Hook {#transformitems-hook} + +`sitemap.transformItems` 훅을 사용하여 `sitemap.xml` 파일에 작성되기 전에 사이트맵 아이템을 수정할 수 있습니다. 이 훅은 사이트맵 아이템 배열을 인자로 받고 사이트맵 아이템 배열을 반환해야 합니다. 예제: + +```ts +export default { + sitemap: { + hostname: 'https://example.com', + transformItems: (items) => { + // 새로운 아이템 추가 또는 기존 아이템 수정/필터링 + items.push({ + url: '/extra-page', + changefreq: 'monthly', + priority: 0.8 + }) + return items + } + } +} +``` diff --git a/docs/ko/guide/ssr-compat.md b/docs/ko/guide/ssr-compat.md new file mode 100644 index 00000000..040527d3 --- /dev/null +++ b/docs/ko/guide/ssr-compat.md @@ -0,0 +1,136 @@ +--- +outline: deep +--- + +# SSR 호환성 {#ssr-compatibility} + +VitePress는 Vue의 서버 사이드 렌더링(SSR) 기능을 사용하여 프로덕션 빌드 중에 Node.js에서 애플리케이션을 사전 렌더링합니다. 이는 테마 컴포넌트의 모든 커스텀 코드가 SSR 호환성을 준수해야 함을 의미합니다. + +공식 Vue 문서의 [SSR 섹션](https://vuejs.org/guide/scaling-up/ssr.html)은 SSR이 무엇인지, SSR / SSG 간의 관계, 그리고 SSR 친화적인 코드를 작성할 때의 일반적인 주의 사항에 대해 더 많은 정보를 제공합니다. 핵심 원칙은 Vue 컴포넌트의 `beforeMount` 또는 `mounted` 훅에서만 브라우저 / DOM API에 접근하는 것입니다. + +## `` + +SSR 친화적이지 않은 컴포넌트(예: 커스텀 디렉티브를 포함한 컴포넌트)를 사용하거나 시연하는 경우, 내장된 `` 컴포넌트로 해당 컴포넌트를 래핑할 수 있습니다: + +```md + + + +``` + +## "import" 시 브라우저 API에 접근하는 라이브러리 {#libraries-that-access-browser-api-on-import} + +일부 컴포넌트나 라이브러리는 **"import" 시** 브라우저 API에 접근합니다. "import" 시 브라우저 환경을 가정하는 코드를 사용하려면, 동적 "import"를 사용해야 합니다. + +### Mounted 훅에서 가져오기 {#importing-in-mounted-hook} + +```vue + +``` + +### 조건부 가져오기 {#conditional-import} + +`import.meta.env.SSR` 플래그([Vite 환경 변수](https://vitejs.dev/guide/env-and-mode.html#env-variables)의 일부)를 사용하여 종속성을 조건부로 "import" 할 수도 있습니다: + +```js +if (!import.meta.env.SSR) { + import('./lib-that-access-window-on-import').then((module) => { + // 코드 사용하기 + }) +} +``` + +[`Theme.enhanceApp`](./custom-theme#theme-interface)은 비동기로 사용할 수 있기 때문에, "import" 시 브라우저 API에 접근하는 Vue 플러그인을 조건부로 "import"하고 등록할 수 있습니다: + +```js +// .vitepress/theme/index.js +/** @type {import('vitepress').Theme} */ +export default { + // ... + async enhanceApp({ app }) { + if (!import.meta.env.SSR) { + const plugin = await import('plugin-that-access-window-on-import') + app.use(plugin.default) + } + } +} +``` + +TypeScript를 사용하는 경우: +```ts +// .vitepress/theme/index.ts +import type { Theme } from 'vitepress' + +export default { + // ... + async enhanceApp({ app }) { + if (!import.meta.env.SSR) { + const plugin = await import('plugin-that-access-window-on-import') + app.use(plugin.default) + } + } +} satisfies Theme +``` + +### `defineClientComponent` + +VitePress는 "import" 시 브라우저 API에 접근하는 Vue 컴포넌트를 "import" 할 수 있는 편리한 헬퍼를 제공합니다. + +```vue + + + +``` + +대상 컴포넌트에 props/children/slots를 전달할 수도 있습니다: + +```vue + + + +``` + +대상 컴포넌트는 래퍼 컴포넌트의 mounted 훅에서만 "import" 됩니다. diff --git a/docs/ko/guide/using-vue.md b/docs/ko/guide/using-vue.md new file mode 100644 index 00000000..5c65eeb7 --- /dev/null +++ b/docs/ko/guide/using-vue.md @@ -0,0 +1,256 @@ +# 마크다운에서 Vue 사용하기 {#using-vue-in-markdown} + +VitePress에서는 각 마크다운 파일이 HTML로 컴파일된 후 [Vue 단일 파일 컴포넌트](https://vuejs.org/guide/scaling-up/sfc.html)로 처리됩니다. 이는 마크다운 내에서 Vue 컴포넌트를 사용하거나 동적 템플릿을 사용하거나 ` + +## 마크다운 컨텐츠 + +현재 카운트: {{ count }} + + + + +``` + +::: warning 마크다운에서 ` +``` + +## 텔레포트 사용하기 {#using-teleports} + +VitePress는 현재 body로 텔레포트를 사용하는 SSG만 지원합니다. 다른 대상에 대해 텔레포트를 사용하려면 내장된 `` 컴포넌트로 감싸거나 [`postRender` 훅](../reference/site-config#postrender)을 통해 최종 페이지 HTML의 올바른 위치에 텔레포트 마크업을 삽입할 수 있습니다. + + + +::: details +<<< @/components/ModalDemo.vue +::: + +```md + + +
+ // ... +
+
+
+``` + + + + diff --git a/docs/ko/guide/what-is-vitepress.md b/docs/ko/guide/what-is-vitepress.md new file mode 100644 index 00000000..9ad43c45 --- /dev/null +++ b/docs/ko/guide/what-is-vitepress.md @@ -0,0 +1,57 @@ +# VitePress란 무엇인가? {#what-is-vitepress} + +VitePress는 빠르고 컨텐츠 중심의 웹사이트를 구축하기 위해 설계된 [정적 사이트 생성기](https://en.wikipedia.org/wiki/Static_site_generator) (SSG)입니다. 다시말해 VitePress는 [마크다운](https://en.wikipedia.org/wiki/Markdown)으로 작성된 소스 컨텐츠를 가져와서 테마를 적용하고, 어디에나 쉽게 배포할 수 있는 정적 HTML 페이지를 생성합니다. + +
+ +그냥 한번 사용해보고 싶으신가요? [빠른 시작](./getting-started)으로 건너뛰세요. + +
+ +## 사용 사례 {#use-cases} + +- **문서화** + + 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) 문서는 모두 이 테마를 기반으로 합니다. + + [Vue.js 공식 문서](https://vuejs.org/)도 VitePress 기반으로 되어 있으며, 여러 번역본에 걸쳐 공유되는 커스텀 테마를 사용합니다. + +- **블로그, 포트폴리오 및 마케팅 사이트** + + VitePress는 표준 Vite + Vue 애플리케이션의 개발자 경험을 가진 [커스텀 테마](./custom-theme)를 지원합니다. Vite 기반이기 때문에 Vite 생태계의 풍부한 플러그인을 직접 활용할 수 있습니다. 또한, VitePress는 [데이터 로딩](./data-loading) (로컬 또는 원격) 및 [동적 라우트 생성](./routing#dynamic-routes)을 위한 유연한 API를 제공합니다. 빌드 시점에 데이터를 결정할 수 있다면 거의 모든 것을 구축할 수 있습니다. + + 공식 [Vue.js 블로그](https://blog.vuejs.org/)는 로컬 콘텐츠 기반의 인덱스 페이지를 생성하는 간단한 블로그입니다. + +## 개발자 경험 {#developer-experience} + +VitePress는 마크다운 컨텐츠를 다룰 때 훌륭한 개발자 경험(DX)을 제공하고자 합니다. + +- **[Vite로 작동](https://vitejs.dev/)**: 즉각적인 서버 시작 가능, 페이지 새로고침 없이 즉시(<100ms) 수정 사항 반영. + +- **[내장된 마크다운 확장 기능](./markdown)**: 서문, 표, 구문 강조 등 무엇이든 가능. 특히 VitePress는 코드 블록 작업을 위한 고급 기능을 많이 제공하여 기술적 문서에 이상적. + +- **[Vue로 향상된 마크다운](./using-vue)**: 각 마크다운 페이지는 HTML과 100% 문법 호환성을 가진 Vue [단일 파일 컴포넌트](https://vuejs.org/guide/scaling-up/sfc.html)입니다. Vue 템플릿 기능이나 컴포넌트를 사용하여 정적 콘텐츠에 상호작용 기능을 포함할 수 있습니다. + +## 성능 {#performance} + +전통적인 SSG들과 달리, VitePress로 생성된 웹사이트는 초기 방문 시 정적 HTML을 제공하지만, 이후 사이트 내 탐색에 대해서는 [단일 페이지 애플리케이션](https://en.wikipedia.org/wiki/Single-page_application) (SPA)이 됩니다. 이 모델은 성능에 대한 최적의 균형을 제공합니다: + +- **빠른 초기 로딩** + + 초기 페이지 방문은 사전 렌더링된 HTML을 제공하여 빠른 로딩 속도와 최적의 SEO를 제공합니다. 그 후 페이지를 Vue SPA로 전환하는 JavaScript 번들이 로드됩니다(이것을 "하이드레이션"이라고 함). 일반적으로 SPA 하이드레이션이 느리다고 생각할 수 있지만, Vue 3의 성능과 컴파일러 최적화 덕분에 이 과정은 매우 빠릅니다. [PageSpeed Insights](https://pagespeed.web.dev/report?url=https%3A%2F%2Fvitepress.dev%2F)에서 일반적인 VitePress 사이트는 네트워크 속도가 느린 저가형 모바일 기기에서도 거의 완벽한 성능 점수를 얻습니다. + +- **빠른 포스트 로드 탐색** + + 더 중요한 것은 SPA 모델이 처음 로드된 후 더 나은 UX를 제공한다는 것입니다. 이후 사이트 내에서 탐색을 해도 전체 페이지가 다시 로드되는 현상이 더 이상 발생하지 않습니다. 대신 페이지의 콘텐츠를 불러와 동적으로 업데이트 합니다. 또한 VitePress는 뷰포트 내에 있는 링크의 페이지 청크를 자동으로 미리 가져옵니다. 이렇게 하면 대부분의 경우 유저는 이미 로드된 페이지에서 탐색할 때 새 페이지가 즉시 로드됩니다. + +- **페널티 없는 상호작용** + + 정적 마크다운 내에 내장된 동적 Vue 부분을 하이드레이션 할 수 있도록 각 마크다운 페이지는 Vue 컴포넌트로 처리되고 JavaScript로 컴파일됩니다. 이는 비효율적으로 보일 수 있지만, Vue 컴파일러는 정적 부분과 동적 부분을 분리하여 하이드레이션 비용과 페이로드 크기를 최소화합니다. 초기 페이지 로드 시, 정적 부분은 자동으로 JavaScript 페이로드에서 제거되고 하이드레이션 중 건너뜁니다. + +## VuePress는 어떤가요? {#what-about-vuepress} + +VitePress는 VuePress의 후속 버전 입니다. 원래 VuePress는 Vue 2와 webpack을 기반으로 했습니다. Vue 3와 Vite를 기반으로 한 VitePress는 훨씬 더 나은 DX, 더 나은 프로덕션 성능, 더 다듬어진 기본 테마, 더 유연한 커스터마이징 API를 제공합니다. + +VitePress와 VuePress의 API 차이는 주로 테마와 커스터마이징에 있습니다. 기본 테마를 사용하는 VuePress 1을 사용 중이라면 VitePress로의 마이그레이션은 비교적 간단할 것입니다. + +VuePress 2도 Vue 3와 Vite를 지원하며 VuePress 1과의 호환성을 높이기 위해 많은 노력이 투자되었습니다. 그러나 두 SSG를 병렬로 유지하는 것은 지속 가능하지 않으므로 Vue 팀은 장기적인 관점에서 주요 권장 SSG인 VitePress에 집중하기로 결정했습니다. diff --git a/docs/ko/index.md b/docs/ko/index.md new file mode 100644 index 00000000..50e56e4c --- /dev/null +++ b/docs/ko/index.md @@ -0,0 +1,60 @@ +--- +layout: home + +title: VitePress +titleTemplate: Vite & Vue 기반 정적 사이트 생성기 + +hero: + name: VitePress + text: Vite & Vue 기반 정적 사이트 생성기 + tagline: 단 몇 분 만에 마크다운을 우아한 문서로 변환 + actions: + - theme: brand + text: VitePress란 무엇인가? + link: /ko/guide/what-is-vitepress + - theme: alt + text: 빠른 시작 + link: /ko/guide/getting-started + - theme: alt + text: GitHub + link: https://github.com/vuejs/vitepress + image: + src: /vitepress-logo-large.webp + alt: VitePress + +features: + - icon: 📝 + title: 콘텐츠에 집중 + details: 마크다운으로만 아름다운 문서 사이트를 쉽게 만들기. + - icon: + title: Vite DX(개발자 경험) 즐겨보기 + details: 즉각적인 서버 시작, 매우 빠른 업데이트, Vite 생태계 플러그인을 활용. + - icon: + title: Vue로 커스터마이징 + details: Vue 문법과 컴포넌트를 마크다운에서 직접 사용하거나 Vue로 커스텀 테마를 구축. + - icon: 🚀 + title: 웹사이트를 빠르게 제공 + details: 정적 HTML로 빠른 초기 로딩, 클라이언트 측 라우팅을 통한 빠른 탐색. +--- + + diff --git a/docs/ko/reference/cli.md b/docs/ko/reference/cli.md new file mode 100644 index 00000000..4a76bd01 --- /dev/null +++ b/docs/ko/reference/cli.md @@ -0,0 +1,74 @@ +# 명령 줄 인터페이스 {#command-line-interface} + +## `vitepress dev` + +지정된 디렉터리를 루트로 하여 VitePress 개발 서버를 시작합니다. 기본값은 현재 디렉터리입니다. 현재 디렉터리에서 실행할 때 `dev` 명령은 생략할 수 있습니다. + +### 사용법 {#usage} + +```sh +# 현재 디렉토리에서 시작, `dev` 생략 +vitepress + +# 하위 디렉터리에서 시작 +vitepress dev [root] +``` + +### 옵션 {#options} + +| 옵션 | 설명 | +| ---------------- | ----------------------------------------------------------------- | +| `--open [path]` | 시작 시 브라우저 열기 (`boolean \| string`) | +| `--port ` | 포트 지정 (`number`) | +| `--base ` | Public 기본 경로 (기본값: `/`) (`string`) | +| `--cors` | CORS 활성화 | +| `--strictPort` | 지정된 포트가 이미 사용 중인 경우 종료 (`boolean`) | +| `--force` | 옵티마이저가 캐시를 무시하고 다시 번들링하도록 강제 (`boolean`) | + +## `vitepress build` + +VitePress 사이트를 프로덕션 빌드합니다. + +### 사용법 {#usage-1} + +```sh +vitepress build [root] +``` + +### 옵션 {#options-1} + +| 옵션 | 설명 | +| ----------------------------- |---------------------------------------------------------------------------------------------| +| `--mpa` (실험적) | 클라이언트 측 하이드레이션 없이 [MPA 모드](../guide/mpa-mode)로 빌드 (`boolean`) | +| `--base ` | Public 기본 경로 (기본값: `/`) (`string`) | +| `--target ` | 트랜스파일 대상 (기본값: `"modules"`) (`string`) | +| `--outDir ` | **cwd** 기준 출력 디렉터리 (기본값: `/.vitepress/dist`) (`string`) | +| `--minify [minifier]` | minify 활성화/비활성화 또는 사용할 minify 도구 지정 (기본값: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | +| `--assetsInlineLimit `| 바이트 단위의 정적 에셋 base64 인라인 임계값 (기본값: `4096`) (`number`) | + +## `vitepress preview` + +프로덕션 빌드를 로컬에서 미리 보기 합니다. + +### 사용법 {#usage-2} + +```sh +vitepress preview [root] +``` + +### 옵션 {#options-2} + +| 옵션 | 설명 | +| ---------------- | ----------------------------------------- | +| `--base ` | Public 기본 경로 (기본값: `/`) (`string`) | +| `--port ` | 포트 지정 (`number`) | + +## `vitepress init` + +현재 디렉터리에서 [설정 마법사](../guide/getting-started#setup-wizard)를 시작합니다. + +### 사용법 {#usage-3} + +```sh +vitepress init +``` diff --git a/docs/ko/reference/default-theme-badge.md b/docs/ko/reference/default-theme-badge.md new file mode 100644 index 00000000..20bdcef9 --- /dev/null +++ b/docs/ko/reference/default-theme-badge.md @@ -0,0 +1,69 @@ +# 배지 {#badge} + +배지는 헤더에 상태를 추가할 수 있게 해줍니다. 예를 들어, 섹션의 타입을 지정하거나 지원되는 버전을 표시하는 데 유용할 수 있습니다. + +## 사용법 {#usage} + +`Badge` 컴포넌트는 전역으로 사용 가능합니다. + +```html +### 제목 +### 제목 +### 제목 +### 제목 +``` + +위 코드는 다음과 같이 렌더링됩니다: + +### 제목 +### 제목 +### 제목 +### 제목 + +## 커스텀 하위 노드 {#custom-children} + +``는 `children`을 받아서 배지 내부에 표시합니다. + +```html +### 제목 커스텀 노드 +``` + +### 제목 커스텀 노드 + +## 타입 색상 커스터마이징 {#customize-type-color} + +배지의 스타일은 CSS 변수를 재정의하여 커스터마이징 할 수 있습니다. 다음은 기본값입니다: + +```css +:root { + --vp-badge-info-border: transparent; + --vp-badge-info-text: var(--vp-c-text-2); + --vp-badge-info-bg: var(--vp-c-default-soft); + + --vp-badge-tip-border: transparent; + --vp-badge-tip-text: var(--vp-c-brand-1); + --vp-badge-tip-bg: var(--vp-c-brand-soft); + + --vp-badge-warning-border: transparent; + --vp-badge-warning-text: var(--vp-c-warning-1); + --vp-badge-warning-bg: var(--vp-c-warning-soft); + + --vp-badge-danger-border: transparent; + --vp-badge-danger-text: var(--vp-c-danger-1); + --vp-badge-danger-bg: var(--vp-c-danger-soft); +} +``` + +## `` + +`` 컴포넌트는 다음과 같은 프로퍼티를 사용합니다: + +```ts +interface Props { + // ``이 전달되면, 이 값은 무시됨. + text?: string + + // 기본값: `tip`. + type?: 'info' | 'tip' | 'warning' | 'danger' +} +``` diff --git a/docs/ko/reference/default-theme-carbon-ads.md b/docs/ko/reference/default-theme-carbon-ads.md new file mode 100644 index 00000000..6a677289 --- /dev/null +++ b/docs/ko/reference/default-theme-carbon-ads.md @@ -0,0 +1,22 @@ +# 카본 광고 {#carbon-ads} + +VitePress는 [카본 광고](https://www.carbonads.net/)에 대한 기본적인 지원을 제공합니다. 구성에서 카본 광고 자격 증명을 정의하면 VitePress는 페이지에 광고를 표시합니다. + +```js +export default { + themeConfig: { + carbonAds: { + code: 'your-carbon-code', + placement: 'your-carbon-placement' + } + } +} +``` + +이 값들은 아래와 같이 카본 CDN 스크립트를 호출하는 데 사용됩니다. + +```js +`//cdn.carbonads.com/carbon.js?serve=${code}&placement=${placement}` +``` + +카본 광고 구성에 대해 더 알고 싶다면 [카본 광고 웹사이트](https://www.carbonads.net/)를 방문하세요. diff --git a/docs/ko/reference/default-theme-config.md b/docs/ko/reference/default-theme-config.md new file mode 100644 index 00000000..b9ae6987 --- /dev/null +++ b/docs/ko/reference/default-theme-config.md @@ -0,0 +1,465 @@ +# 기본 테마 구성 {#default-theme-config} + +테마 구성은 테마를 커스텀 할 수 있게 해줍니다. 구성 파일에서 `themeConfig` 옵션을 통해 테마 구성을 정의할 수 있습니다: + +```ts +export default { + lang: 'ko-KR', + title: 'VitePress', + description: 'Vite 및 Vue로 기반 정적 사이트 생성기.', + + // 테마 관련 구성. + themeConfig: { + logo: '/logo.svg', + nav: [...], + sidebar: { ... } + } +} +``` + +**이 페이지에 문서화된 옵션은 기본 테마에만 적용됩니다.** 다른 테마는 다른 테마 구성이 필요합니다. 커스텀 테마를 사용하는 경우, 테마 구성 객체는 테마에 전달되어 테마가 이를 기반으로 다르게 동작할 수 있습니다. + +## i18nRouting + +- 타입: `boolean` + +로케일을 `ko`로 변경하면 URL이 `/foo` (또는 `/en/foo/`)에서 `/ko/foo`로 변경됩니다. 이 동작을 비활성화하려면 `themeConfig.i18nRouting`을 `false`로 설정하세요. + +## logo + +- 타입: `ThemeableImage` + +네비게이션 바에 사이트 제목 바로 앞에 표시할 로고 파일입니다. 경로 문자열 또는 라이트/다크 모드에 대해 다른 로고를 설정할 수 있는 객체를 사용합니다. + +```ts +export default { + themeConfig: { + logo: '/logo.svg' + } +} +``` + +```ts +type ThemeableImage = + | string + | { src: string; alt?: string } + | { light: string; dark: string; alt?: string } +``` + +## siteTitle + +- 타입: `string | false` + +이 항목을 커스텀하여 네비게이션 바의 기본 사이트 제목(애플리케이션 구성의 `title`)을 대체할 수 있습니다. `false`로 설정하면 네비게이션 바에서 제목이 비활성화됩니다. 이미 사이트 제목 텍스트가 포함된 `logo`가 있을 때 유용합니다. + +```ts +export default { + themeConfig: { + siteTitle: 'Hello World' + } +} +``` + +## nav + +- 타입: `NavItem` + +네비게이션 바 메뉴 아이템의 구성입니다. 자세한 내용은 [기본 테마: 네비게이션 바](./default-theme-nav#navigation-links)를 참고하세요. + +```ts +export default { + themeConfig: { + nav: [ + { text: '가이드', link: '/guide' }, + { + text: '드롭다운 메뉴', + items: [ + { text: '항목 A', link: '/item-1' }, + { text: '항목 B', link: '/item-2' }, + { text: '항목 C', link: '/item-3' } + ] + } + ] + } +} +``` + +```ts +type NavItem = NavItemWithLink | NavItemWithChildren + +interface NavItemWithLink { + text: string + link: string + activeMatch?: string + target?: string + rel?: string + noIcon?: boolean +} + +interface NavItemChildren { + text?: string + items: NavItemWithLink[] +} + +interface NavItemWithChildren { + text?: string + items: (NavItemChildren | NavItemWithLink)[] + activeMatch?: string +} +``` + +## sidebar + +- 타입: `Sidebar` + +사이드바 메뉴 항목에 대한 구성입니다. 자세한 내용은 [기본 테마: 사이드바](./default-theme-sidebar)에서 확인하세요. + +```ts +export default { + themeConfig: { + sidebar: [ + { + text: '가이드', + items: [ + { text: '소개', link: '/introduction' }, + { text: '시작하기', link: '/getting-started' }, + ... + ] + } + ] + } +} +``` + +```ts +export type Sidebar = SidebarItem[] | SidebarMulti + +export interface SidebarMulti { + [path: string]: SidebarItem[] | { items: SidebarItem[]; base: string } +} + +export type SidebarItem = { + /** + * 아이템의 텍스트 레이블 + */ + text?: string + + /** + * 아이템의 링크 + */ + link?: string + + /** + * 아이템의 하위 항목 + */ + items?: SidebarItem[] + + /** + * 명시하지 않은 경우, 그룹을 접을 수 없습니다. + * + * `true`: 그룹은 접을 수 있고 기본적으로 접혀 있습니다. + * + * `false`: 그룹은 접을 수 있고 기본적으로 펼쳐져 있습니다. + */ + collapsed?: boolean + + /** + * 하위 아이템에 대한 기본 경로입니다. + */ + base?: string + + /** + * 이전/다음 페이지의 푸터에 나타나는 텍스트를 커스텀 합니다. + */ + docFooterText?: string + + rel?: string + target?: string +} +``` + +## aside + +- 타입: `boolean | 'left'` +- 기본값: `true` +- [전문](./frontmatter-config#aside)을 통해 페이지별로 재정의할 수 있습니다. + +`false`: 어사이드 컨테이너가 렌더링되지 않습니다.\ +`true`: 어사이드가 오른쪽에 렌더링됩니다.\ +`left`: 어사이드가 왼쪽에 렌더링됩니다. + +모든 뷰포트에서 비활성화하려면 `outline: false`를 사용해야 합니다. + +## outline + +- 타입: `Outline | Outline['level'] | false` +- [전문](./frontmatter-config#outline)을 사용해 각 페이지별로 계층 구조를 재정의할 수 있습니다. + +이 값을 `false`로 설정하면 아웃라인(개요) 컨테이너가 렌더링되지 않습니다. 자세한 내용은 아래 인터페이스를 참고하세요: + +```ts +interface Outline { + /** + * 아웃라인에 표시할 제목 레벨. + * 단일 숫자는 해당 레벨의 제목만 표시됨을 의미합니다. + * 튜플이 전달되면, 첫 번째 숫자는 최소 수준을, 두 번째 숫자는 최대 수준을 나타냅니다. + * `'deep'`은 `[2, 6]`과 동일하며, 이는 `

`에서 `

`까지의 모든 제목이 표시됨을 의미합니다. + * + * @default 2 + */ + level?: number | [number, number] | 'deep' + + /** + * 아웃라인에 표시될 제목. + * + * @default 'On this page' + */ + label?: string +} +``` + +## socialLinks + +- 타입: `SocialLink[]` + +이 옵션을 정의하여 네비게이션 바에 소셜 링크를 아이콘과 함께 표시할 수 있습니다. + +```ts +export default { + themeConfig: { + socialLinks: [ + { icon: 'github', link: 'https://github.com/vuejs/vitepress' }, + { icon: 'twitter', link: '...' }, + // SVG를 문자열로 전달하여 커스텀 아이콘을 추가할 수도 있습니다: + { + icon: { + svg: '' + }, + link: '...', + // 접근성을 위해 커스텀 레이블을 포함할 수도 있습니다 (선택 사항이지만 권장됨): + ariaLabel: '스타 링크' + } + ] + } +} +``` + +```ts +interface SocialLink { + icon: SocialLinkIcon + link: string + ariaLabel?: string +} + +type SocialLinkIcon = + | 'discord' + | 'facebook' + | 'github' + | 'instagram' + | 'linkedin' + | 'mastodon' + | 'npm' + | 'slack' + | 'twitter' + | 'x' + | 'youtube' + | { svg: string } +``` + +## footer + +- 타입: `Footer` +- [전문](./frontmatter-config#footer)을 사용해 페이지별로 재정의할 수 있습니다. + +푸터 구성입니다. 메시지 또는 저작권 텍스트를 푸터에 추가할 수 있지만, 이는 페이지에 사이드바가 포함되지 않은 경우에만 표시됩니다. 이는 디자인상의 이유 때문입니다. + +```ts +export default { + themeConfig: { + footer: { + message: 'MIT 라이선스에 따라 릴리즈되었습니다.', + copyright: '저작권 © 2019-현재 홍길동' + } + } +} +``` + +```ts +export interface Footer { + message?: string + copyright?: string +} +``` + +## editLink + +- 타입: `EditLink` +- [전문](./frontmatter-config#footer)을 사용해 페이지별로 재정의할 수 있습니다. + +편집 링크 기능을 사용하면 GitHub 또는 GitLab과 같은 Git 관리 서비스에서 페이지를 편집할 수 있는 링크를 표시할 수 있습니다. 자세한 내용은 [기본 테마: 편집 링크](./default-theme-edit-link)를 참고하세요. + +```ts +export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'GitHub에서 이 페이지 편집하기' + } + } +} +``` + +```ts +export interface EditLink { + pattern: string + text?: string +} +``` + +## lastUpdated + +- 타입: `LastUpdatedOptions` + +마지막 업데이트된 날짜의 텍스트와 날짜 형식을 커스텀 할 수 있습니다. + +```ts +export default { + themeConfig: { + lastUpdated: { + text: '마지막 업데이트 날짜', + formatOptions: { + dateStyle: 'full', + timeStyle: 'medium' + } + } + } +} +``` + +```ts +export interface LastUpdatedOptions { + /** + * @default 'Last updated' + */ + text?: string + + /** + * @default + * {dateStyle: 'short', timeStyle: 'short'} + */ + formatOptions?: Intl.DateTimeFormatOptions & { forceLocale?: boolean } +} +``` + +## algolia + +- 타입: `AlgoliaSearch` + +[Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch)를 사용하여 문서 사이트를 검색할 수 있는 옵션입니다. 자세한 내용은 [기본 테마: 검색](./default-theme-search)을 참고하세요. + +```ts +export interface AlgoliaSearchOptions extends DocSearchProps { + locales?: Record> +} +``` + +전체 옵션은 [여기](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts)에서 확인하세요. + +## carbonAds {#carbon-ads} + +- 타입: `CarbonAdsOptions` + +[Carbon Ads](https://www.carbonads.net/)를 표시할 수 있는 옵션입니다. + +```ts +export default { + themeConfig: { + carbonAds: { + code: 'your-carbon-code', + placement: 'your-carbon-placement' + } + } +} +``` + +```ts +export interface CarbonAdsOptions { + code: string + placement: string +} +``` + +자세한 내용은 [기본 테마: 카본 광고](./default-theme-carbon-ads)를 참고하세요. + +## docFooter + +- 타입: `DocFooter` + +이 옵션은 이전 및 다음 링크에 표시되는 텍스트를 커스텀하는 데 사용합니다. 영어로 문서를 작성하지 않는 경우 유용합니다. 또한 이전/다음 링크를 전역적으로 비활성화할 수도 있습니다. 선택적으로 이전/다음 링크를 활성화/비활성화하려면 [전문](./default-theme-prev-next-links)을 사용합니다. + +```ts +export default { + themeConfig: { + docFooter: { + prev: '이전 페이지', + next: '다음 페이지' + } + } +} +``` + +```ts +export interface DocFooter { + prev?: string | false + next?: string | false +} +``` + +## darkModeSwitchLabel + +- 타입: `string` +- 기본값: `Appearance` + +이 옵션은 다크 모드 스위치 레이블을 커스텀할 때 사용합니다. 이 레이블은 모바일 뷰에서만 표시됩니다. + +## lightModeSwitchTitle + +- 타입: `string` +- 기본값: `Switch to light theme` + +이 옵션은 라이트 모드 스위치 타이틀을 커스텀할 때 사용합니다. 이것은 호버(hover)할 때 나타납니다. + +## darkModeSwitchTitle + +- 타입: `string` +- 기본값: `Switch to dark theme` + +호버 시 나타나는 다크 모드 스위치 타이틀을 커스텀할 때 사용합니다. + +## sidebarMenuLabel + +- 타입: `string` +- 기본값: `Menu` + +사이드바 메뉴 레이블을 커스텀 할 때 사용합니다. 이 레이블은 모바일 뷰에서만 표시됩니다. + +## returnToTopLabel + +- 타입: `string` +- 기본값: `Return to top` + +맨 위로 이동 버튼의 레이블을 커스텀 할 때 사용합니다. 이 레이블은 모바일 뷰에서만 표시됩니다. + +## langMenuLabel + +- 타입: `string` +- 기본값: `Change language` + +네비게이션 바에서 언어 토글 버튼의 aria-label을 커스텀 할 때 사용합니다. 이는 [i18n](../guide/i18n)을 사용하는 경우에만 사용됩니다. + +## externalLinkIcon + +- 타입: `boolean` +- 기본값: `false` + +마크다운의 외부 링크 옆에 외부 링크 아이콘을 표시할지 여부를 설정합니다. diff --git a/docs/ko/reference/default-theme-edit-link.md b/docs/ko/reference/default-theme-edit-link.md new file mode 100644 index 00000000..4494b937 --- /dev/null +++ b/docs/ko/reference/default-theme-edit-link.md @@ -0,0 +1,60 @@ +# 편집 링크 {#edit-link} + +## 사이트 단계에서 설정하기 {#site-level-config} + +편집 링크는 GitHub, GitLab과 같은 Git 관리 서비스에서 페이지를 편집할 수 있는 링크를 표시할 수 있게 해줍니다. 이를 활성화하려면 `themeConfig.editLink` 옵션을 구성에 추가하세요. + +```js +export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path' + } + } +} +``` + +`pattern` 옵션은 링크의 URL 구조를 정의하며, `:path`는 페이지 경로로 대체됩니다. + +또한, [`PageData`](./runtime-api#usedata)를 인자로 받아 URL 문자열을 반환하는 순수 함수를 사용할 수도 있습니다. + +```js +export default { + themeConfig: { + editLink: { + pattern: ({ filePath }) => { + if (filePath.startsWith('packages/')) { + return `https://github.com/acme/monorepo/edit/main/${filePath}` + } else { + return `https://github.com/acme/monorepo/edit/main/docs/${filePath}` + } + } + } + } +} +``` + +이 함수는 브라우저에서 직렬화되어 실행되므로, 부작용을 가지지 않고 해당 스코프 외부의 어떤 것도 참조하지 않도록 해야 합니다. + +기본적으로 이 설정은 문서 페이지 하단에 "Edit this page"이라는 텍스트 링크를 추가합니다. 이 텍스트는 `text` 옵션을 정의하여 커스터마이징 할 수 있습니다. + +```js +export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: '이 페이지 편집 제안하기' + } + } +} +``` + +## 전문에서 설정하기 {#frontmatter-config} + +페이지별로 이 기능을 비활성화하려면, 전문에서 `editLink` 옵션을 사용하세요: + +```yaml +--- +editLink: false +--- +``` diff --git a/docs/ko/reference/default-theme-footer.md b/docs/ko/reference/default-theme-footer.md new file mode 100644 index 00000000..de808252 --- /dev/null +++ b/docs/ko/reference/default-theme-footer.md @@ -0,0 +1,53 @@ +# 푸터 {#footer} + +`themeConfig.footer`가 존재하면 VitePress는 페이지 하단에 전역 푸터를 표시합니다. + +```ts +export default { + themeConfig: { + footer: { + message: 'MIT 라이선스에 따라 릴리즈되었습니다.', + copyright: '저작권 © 2019-현재 홍길동' + } + } +} +``` + +```ts +export interface Footer { + // 저작권 전에 표시되는 메시지. + message?: string + + // 실제 저작권 텍스트. + copyright?: string +} +``` + +위의 구성은 HTML 문자열도 지원합니다. 예를 들어, 푸터 텍스트에 링크를 포함하고 싶다면, 다음과 같이 구성을 수정하면 됩니다: + +```ts +export default { + themeConfig: { + footer: { + message: 'MIT 라이선스에 따라 릴리즈되었습니다.', + copyright: '저작권 © 2019-현재 홍길동' + } + } +} +``` + +::: warning +`message`와 `copyright`는 `

` 엘리먼트 내부에 렌더링되므로 인라인 엘리먼트만 사용할 수 있습니다. 블록 엘리먼트를 추가하려면 [`layout-bottom`](../guide/extending-default-theme#layout-slots) 슬롯을 사용하는 것이 좋습니다. +::: + +[사이드바](./default-theme-sidebar)가 표시되는 경우 푸터는 표시되지 않습니다. + +## 전문에서 설정하기 {#frontmatter-config} + +이 기능은 전문의 `footer` 옵션을 사용하여 페이지별로 비활성화 할 수 있습니다. + +```yaml +--- +footer: false +--- +``` diff --git a/docs/ko/reference/default-theme-home-page.md b/docs/ko/reference/default-theme-home-page.md new file mode 100644 index 00000000..51550279 --- /dev/null +++ b/docs/ko/reference/default-theme-home-page.md @@ -0,0 +1,195 @@ +# 홈 페이지 {#home-page} + +VitePress 기본 테마는 홈 페이지 레이아웃을 제공합니다. 이것은 이 사이트의 [홈 페이지](../)에도 사용되었습니다. `layout: home`을 [전문](./frontmatter-config)에 지정하여 어느 페이지에서도 이를 사용할 수 있습니다. + +```yaml +--- +layout: home +--- +``` + +하지만 이 옵션만으로는 많은 것을 할 수 없습니다. 다행히도 `hero` 및 `features`와 같은 추가 옵션을 설정하여 홈 페이지에 다양한 사전 템플릿 "섹션"들을 추가할 수 있습니다. + +## Hero 섹션 {#hero-section} + +Hero 섹션은 홈 페이지의 상단에 위치합니다. Hero 섹션을 구성하는 방법은 다음과 같습니다. + +```yaml +--- +layout: home + +hero: + name: VitePress + text: Vite & Vue 기반 정적 사이트 생성기 + tagline: 단 몇 분 만에 마크다운을 우아한 문서로 변환 + image: + src: /logo.png + alt: VitePress + actions: + - theme: brand + text: VitePress란 무엇인가? + link: /guide/what-is-vitepress + - theme: alt + text: GitHub + link: https://github.com/vuejs/vitepress +--- +``` + +```ts +interface Hero { + // `text` 위에 브랜드 색상으로 표시되는 문자열. + // 제품명 등 간략한 내용을 추천. + name?: string + + // hero 섹션의 본문. + // `h1` 태그로 정의됨. + text: string + + // `text` 아래에 표시되는 슬로건 문자열. + tagline?: string + + // `text` 및 `tagline` 옆에 표시되는 이미지. + image?: ThemeableImage + + // hero 섹션에 표시할 버튼 리스트. + actions?: HeroAction[] +} + +type ThemeableImage = + | string + | { src: string; alt?: string } + | { light: string; dark: string; alt?: string } + +interface HeroAction { + // 버튼의 색상 테마. 기본값: `brand` + theme?: 'brand' | 'alt' + + // 버튼의 레이블. + text: string + + // 버튼의 목적지 링크. + link: string + + // 링크의 target 어트리뷰트. + target?: string + + // 링크의 rel 어트리뷰트. + rel?: string +} +``` + +### `name` 색상 커스터마이징 {#customizing-the-name-color} + +VitePress는 `name`에 브랜드 색상(`--vp-c-brand-1`)을 사용합니다. 하지만 `--vp-home-hero-name-color` 변수를 재정의하여 이 색상을 커스텀 할 수 있습니다. + +```css +:root { + --vp-home-hero-name-color: blue; +} +``` + +또한 `--vp-home-hero-name-background` 변수를 정의해 추가적으로 `name`을 그라데이션 색상으로 커스터마이징도 가능합니다. + +```css +:root { + --vp-home-hero-name-color: transparent; + --vp-home-hero-name-background: -webkit-linear-gradient(120deg, #bd34fe, #41d1ff); +} +``` + +## Features 섹션 {#features-section} + +Features 섹션에서는 Hero 섹션 바로 아래에 표시할 각 feature를 원하는 만큼 나열할 수 있습니다. 이를 구성하려면 `features` 옵션을 전문에 전달하면 됩니다. + +각 feature에 아이콘을 제공할 수 있으며, 이는 이모지 또는 이미지의 형태일 수 있습니다. 아이콘으로 이미지(svg, png, jpeg 등)를 사용하려면 적절한 너비와 높이를 제공해야 하며, 필요에 따라 설명, 이미지의 고유 크기, 다크 테마와 라이트 테마에 대한 변형 아이콘도 제공할 수 있습니다. + +```yaml +--- +layout: home + +features: + - icon: 🛠️ + title: Simple and minimal, always + details: Lorem ipsum... + - icon: + src: /cool-feature-icon.svg + title: Another cool feature + details: Lorem ipsum... + - icon: + dark: /dark-feature-icon.svg + light: /light-feature-icon.svg + title: Another cool feature + details: Lorem ipsum... +--- +``` + +```ts +interface Feature { + // 각 feature 박스에 표시할 아이콘. + icon?: FeatureIcon + + // feature의 제목. + title: string + + // feature의 세부 정보. + details: string + + // feature 컴포넌트 클릭 시 링크. + // 링크는 내부 또는 외부 모두 가능. + // + // 예: `guide/reference/default-theme-home-page` 또는 `https://example.com` + link?: string + + // feature 컴포넌트 내 표시될 링크 텍스트. + // `link` 옵션과 함께 사용하는 것을 추천. + // + // 예: `더 알아보기`, `페이지 방문` 등 + linkText?: string + + // `link` 옵션을 위한 링크 rel 어트리뷰트. + // + // 예: `external` + rel?: string + + // `link` 옵션을 위한 링크 target 어트리뷰트. + target?: string +} + +type FeatureIcon = + | string + | { src: string; alt?: string; width?: string; height: string } + | { + light: string + dark: string + alt?: string + width?: string + height: string + } +``` + +## 마크다운 컨텐츠 {#markdown-content} + +홈 페이지 레이아웃에 추가 컨텐츠를 작성하려면 전문 구분선 `---` 아래에 마크다운을 추가하면 됩니다. + +````md +--- +layout: home + +hero: + name: VitePress + text: Vite & Vue 기반 정적 사이트 생성기 +--- + +## 시작하기 + +`npx`를 사용하여 VitePress를 바로 시작할 수 있습니다! + +```sh +npm init +npx vitepress init +``` +```` + +::: info +`layout: home` 페이지의 추가 컨텐츠에 자동으로 기본 마크다운 스타일이 적용됩니다(영문 원서에서는 반대로 설명함). 스타일을 적용하지 않으려면 전문에 `markdownStyles: false`를 추가하면 됩니다. +::: diff --git a/docs/ko/reference/default-theme-last-updated.md b/docs/ko/reference/default-theme-last-updated.md new file mode 100644 index 00000000..2d4760e0 --- /dev/null +++ b/docs/ko/reference/default-theme-last-updated.md @@ -0,0 +1,27 @@ +# 마지막 업데이트 날짜 {#last-updated} + +마지막 업데이트 날짜는 페이지 오른쪽 하단에 표시됩니다. 이를 활성화하려면 구성 파일에 `lastUpdated` 옵션을 추가하세요. + +::: tip +마크다운 파일을 커밋해야 업데이트된 시간을 확인할 수 있습니다. +::: + +## 사이트 단계에서 설정하기 {#site-level-config} + +```js +export default { + lastUpdated: true +} +``` + +## 전문에서 설정하기 {#frontmatter-config} + +페이지별로 이 기능을 비활성화하려면, 전문에서 `lastUpdated` 옵션을 사용하세요: + +```yaml +--- +lastUpdated: false +--- +``` + +자세한 내용은 [기본 테마: lastUpdated](./default-theme-config#lastupdated)를 참고하세요. 테마 레벨에서 참(truthy) 값을 설정하면, 사이트나 페이지 레벨에서 명시적으로 비활성화하지 않는 한 이 기능이 활성화됩니다. diff --git a/docs/ko/reference/default-theme-layout.md b/docs/ko/reference/default-theme-layout.md new file mode 100644 index 00000000..cf97f416 --- /dev/null +++ b/docs/ko/reference/default-theme-layout.md @@ -0,0 +1,62 @@ +# 레이아웃 {#layout} + +페이지의 [전문](./frontmatter-config)에 `layout` 옵션을 설정하여 페이지 레이아웃을 선택할 수 있습니다. `doc`, `page`, `home` 세 가지 레이아웃 옵션이 있습니다. 아무것도 지정하지 않으면 `doc` 페이지로 처리됩니다. + +```yaml +--- +layout: doc +--- +``` + +## `doc` 레이아웃 {#doc-layout} + +`doc` 옵션은 기본 레이아웃으로, 전체 마크다운 콘텐츠를 "문서" 스타일로 변환합니다. 이 레이아웃은 전체 콘텐츠를 `vp-doc` CSS 클래스로 감싸고, 하위 엘리먼트에 스타일을 적용하는 방식으로 작동합니다. + +`p`나 `h2` 같은 거의 모든 일반적인 엘리먼트들이 특별한 스타일을 갖게 됩니다. 따라서 마크다운 콘텐츠에 커스텀 HTML을 추가할 경우, 해당 HTML도 이러한 스타일의 영향을 받게 된다는 점을 유념해야 합니다. + +이 레이아웃에서는 아래에 나열된 문서 전용 기능들도 제공됩니다. 이 기능들은 오직 이 레이아웃에서만 활성화됩니다. + +- 편집 링크 +- 이전/다음 링크 +- 개요(outline) +- [카본 광고](./default-theme-carbon-ads) + +## `page` 레이아웃 {#page-layout} + +`page` 옵션은 "빈 페이지"로 처리됩니다. 마크다운은 여전히 파싱되며, 모든 [마크다운 확장 기능](../guide/markdown)이 `doc` 레이아웃과 동일하게 작동하지만, 기본 스타일링은 적용되지 않습니다. + +이 페이지 레이아웃은 VitePress 테마가 마크업에 영향을 미치지 않도록 하여, 모든 스타일을 직접 지정할 수 있게 해줍니다. 이는 커스텀 페이지를 만들고자 할 때 유용합니다. + +이 레이아웃에서도 페이지에 매칭되는 사이드바 구성이 있는 경우 사이드바는 여전히 표시됩니다. + +## `home` 레이아웃 {#home-layout} + +`home` 옵션은 템플릿화된 "홈 페이지"를 생성합니다. 이 레이아웃에서는 `hero`와 `features` 같은 추가 옵션을 설정하여 콘텐츠를 더 커스터마이징 할 수 있습니다. 자세한 내용은 [기본 테마: 홈 페이지](./default-theme-home-page)를 참고하세요. + +## 레이아웃 없음 {#no-layout} + +어떤 레이아웃도 원하지 않는 경우, 전문에 `layout: false`를 전달할 수 있습니다. 이 옵션은 (기본적으로 사이드바, 네비게이션 바, 또는 푸터가 없는) 완전히 커스터마이징 가능한 랜딩 페이지를 만들고자 할 때 유용합니다. + +## 커스텀 레이아웃 {#custom-layout} + +커스텀 레이아웃을 사용할 수도 있습니다: + +```md +--- +layout: foo +--- +``` + +이것은 컨텍스트에 등록된 `foo`라는 이름의 컴포넌트를 찾습니다. 예를 들어 `.vitepress/theme/index.ts`에서 컴포넌트를 전역으로 등록할 수 있습니다: + +```ts +import DefaultTheme from 'vitepress/theme' +import Foo from './Foo.vue' + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('foo', Foo) + } +} +``` diff --git a/docs/ko/reference/default-theme-nav.md b/docs/ko/reference/default-theme-nav.md new file mode 100644 index 00000000..5acb88d8 --- /dev/null +++ b/docs/ko/reference/default-theme-nav.md @@ -0,0 +1,216 @@ +# 네비게이션 바 {#nav} + +네비게이션 바는 페이지 상단에 표시되며, 사이트 제목, 전역 메뉴 링크 등이 포함됩니다. + +## 사이트 제목 및 로고 {#site-title-and-logo} + +기본적으로 네비게이션 바는 [`config.title`](./site-config#title) 값을 참조하여 사이트 제목을 표시합니다. 여기에 표시되는 내용을 변경하려면 `themeConfig.siteTitle` 옵션에 커스텀 텍스트를 정의합니다. + +```js +export default { + themeConfig: { + siteTitle: 'My Custom Title' + } +} +``` + +사이트에 로고가 있는 경우, 이미지의 경로를 전달하여 로고를 표시할 수 있습니다. 로고는 `public` 폴더에 배치하고, 이것의 절대 경로를 정의해야 합니다. + +```js +export default { + themeConfig: { + logo: '/my-logo.svg' + } +} +``` + +로고를 추가하면 사이트 제목과 함께 표시됩니다. 로고만 필요하고 사이트 제목 텍스트를 숨기고 싶다면, `siteTitle` 옵션을 `false`로 설정하면 됩니다. + +```js +export default { + themeConfig: { + logo: '/my-logo.svg', + siteTitle: false + } +} +``` + +로고에 `alt` 어트리뷰트를 추가하거나 다크/라이트 모드에 따라 커스터마이징 하려면, 로고를 객체 형태로 전달해야 합니다. 자세한 내용은 [`themeConfig.logo`](./default-theme-config#logo)를 참고하세요. + +## 네비게이션 바 링크 {#navigation-links} + +`themeConfig.nav` 옵션을 정의하여 네비게이션 바에 링크를 추가할 수 있습니다. + +```js +export default { + themeConfig: { + nav: [ + { text: '가이드', link: '/guide' }, + { text: '구성', link: '/config' }, + { text: '변경사항', link: 'https://github.com/...' } + ] + } +} +``` + +`text`는 네비게이션 바에 표시되는 실제 텍스트이며, `link`는 텍스트를 클릭했을 때 이동할 링크입니다. 링크의 경로는 `.md` 접미사 없이 실제 파일 경로로 설정하며, 항상 `/`로 시작해야 합니다. + +네비게이션 바 링크는 드롭다운 메뉴가 될 수 있습니다. 이를 위해 `link` 옵션에 `items` 키를 설정합니다. + +```js +export default { + themeConfig: { + nav: [ + { text: '가이드', link: '/guide' }, + { + text: '드롭다운 메뉴', + items: [ + { text: '항목 A', link: '/item-1' }, + { text: '항목 B', link: '/item-2' }, + { text: '항목 C', link: '/item-3' } + ] + } + ] + } +} +``` + +드롭다운 메뉴의 제목(위 예제에서 `드롭다운 메뉴`)은 드롭다운 대화 상자를 여는 버튼이 되므로 `link` 프로퍼티를 가질 수 없습니다. + +드롭다운 메뉴 아이템에 더 많은 중첩된 아이템을 전달하여 "섹션"을 추가할 수도 있습니다. + +```js +export default { + themeConfig: { + nav: [ + { text: '가이드', link: '/guide' }, + { + text: '드롭다운 메뉴', + items: [ + { + // 섹션의 제목. + text: '섹션 A 제목', + items: [ + { text: '섹션 A 항목 A', link: '...' }, + { text: '섹션 B 항목 B', link: '...' } + ] + } + ] + }, + { + text: '드롭다운 메뉴', + items: [ + { + // 제목을 생략할 수도 있습니다. + items: [ + { text: '섹션 A 항목 A', link: '...' }, + { text: '섹션 B 항목 B', link: '...' } + ] + } + ] + } + ] + } +} +``` + +### 링크의 "active" 상태 커스터마이징 {#customize-link-s-active-state} + +네비게이션 바 메뉴 아이템은 현재 페이지가 매칭되는 경로에 있을 때 강조 표시됩니다. 매칭할 경로를 커스터마이징 하려면 `activeMatch` 프로퍼티에 정규식을 문자열 값으로 정의합니다. + +```js +export default { + themeConfig: { + nav: [ + // `/config/` 경로에 있을 때 + // 이 링크는 활성화된 상태가 됩니다. + { + text: '가이드', + link: '/guide', + activeMatch: '/config/' + } + ] + } +} +``` + +::: warning +`activeMatch`는 정규식이어야 하지만, 문자열로 정의해야 합니다. 실제 RegExp 객체를 사용할 수 없는 이유는 빌드하는 동안 직렬화할 수 없기 때문입니다. +::: + +### 링크의 "target" 및 "rel" 어트리뷰트 커스터마이징 {#customize-link-s-target-and-rel-attributes} + +기본적으로 VitePress는 링크가 외부 링크인지 여부에 따라 `target`과 `rel` 어트리뷰트를 자동으로 결정합니다. 하지만 원한다면 이를 커스터마이징 할 수도 있습니다. + +```js +export default { + themeConfig: { + nav: [ + { + text: 'GitHub 쇼핑몰', + link: 'https://www.thegithubshop.com/', + target: '_self', + rel: 'sponsored' // https://developers.google.com/search/docs/crawling-indexing/qualify-outbound-links + } + ] + } +} +``` + +## 소셜 링크 {#social-links} + +[`socialLinks`](./default-theme-config#sociallinks)를 참고하세요. + +## 커스텀 컴포넌트 {#custom-components} + +네비게이션 바에 커스텀 컴포넌트를 포함하려면 `component` 옵션을 사용하세요. `component` 키는 Vue 컴포넌트 이름이어야 하며, [Theme.enhanceApp](../guide/custom-theme#theme-interface)을 사용하여 전역적으로 등록해야 합니다. + +```js +// .vitepress/config.js +export default { + themeConfig: { + nav: [ + { + text: 'My Menu', + items: [ + { + component: 'MyCustomComponent', + // 컴포넌트에 전달할 선택적 프로퍼티 + props: { + title: 'My Custom Component' + } + } + ] + }, + { + component: 'AnotherCustomComponent' + } + ] + } +} +``` + +그런 다음, 컴포넌트를 전역적으로 등록해야 합니다: + +```js +// .vitepress/theme/index.js +import DefaultTheme from 'vitepress/theme' + +import MyCustomComponent from './components/MyCustomComponent.vue' +import AnotherCustomComponent from './components/AnotherCustomComponent.vue' + +/** @type {import('vitepress').Theme} */ +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('MyCustomComponent', MyCustomComponent) + app.component('AnotherCustomComponent', AnotherCustomComponent) + } +} +``` + +컴포넌트는 네비게이션 바에 렌더링될 것입니다. VitePress는 컴포넌트에 다음과 같은 추가 프로퍼티를 제공합니다: + +- `screenMenu`: 컴포넌트가 모바일 네비게이션 바 메뉴 내부에 있는지를 나타내는 선택적 boolean 값 + +e2e 테스트 예제를 [여기](https://github.com/vuejs/vitepress/tree/main/__tests__/e2e/.vitepress)에서 확인할 수 있습니다. diff --git a/docs/ko/reference/default-theme-prev-next-links.md b/docs/ko/reference/default-theme-prev-next-links.md new file mode 100644 index 00000000..276ae882 --- /dev/null +++ b/docs/ko/reference/default-theme-prev-next-links.md @@ -0,0 +1,43 @@ +# 이전/다음 링크 {#prev-next-links} + +문서 하단에 표시되는 이전 페이지와 다음 페이지의 텍스트와 링크를 커스터마이징 할 수 있습니다. 사이드바에 있는 텍스트와 다른 텍스트를 원할 경우 유용합니다. 또한 푸터를 비활성화하거나 사이드바에 포함되지 않은 페이지로 링크할 때도 유용할 수 있습니다. + +## prev + +- 타입: `string | false | { text?: string; link?: string }` + +- 세부 사항: + + 이전 페이지로 가는 링크에 표시할 텍스트/링크를 지정합니다. 전문에서 이 항목을 설정하지 않으면, 사이드바 구성에서 텍스트/링크가 유추됩니다. + +- 예제: + + - 텍스트만 커스터마이징하려면: + + ```yaml + --- + prev: '시작하기 | 마크다운' + --- + ``` + + - 텍스트와 링크를 모두 커스터마이즈하려면: + + ```yaml + --- + prev: + text: '마크다운 확장 기능' + link: '/guide/markdown' + --- + ``` + + - 이전 페이지를 숨기려면: + + ```yaml + --- + prev: false + --- + ``` + +## next + +`prev`와 동일하지만, 다음 페이지에 대한 설정입니다. diff --git a/docs/ko/reference/default-theme-search.md b/docs/ko/reference/default-theme-search.md new file mode 100644 index 00000000..9d446a99 --- /dev/null +++ b/docs/ko/reference/default-theme-search.md @@ -0,0 +1,386 @@ +--- +outline: deep +--- + +# 검색 {#search} + +## 로컬 검색 {#local-search} + +VitePress는 [minisearch](https://github.com/lucaong/minisearch/)로 브라우저 내 인덱스를 사용하는 퍼지(full-text) 검색을 지원합니다. 이 기능을 활성화하려면 `.vitepress/config.ts` 파일에서 `themeConfig.search.provider` 옵션을 `'local'`로 설정하면 됩니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local' + } + } +}) +``` + +예제 결과: + +![검색 모달의 스크린샷](/search.png) + +대안으로 [Algolia DocSearch](#algolia-search), , 와 같은 커뮤니티 플러그인을 사용할 수도 있습니다. + +### i18n {#local-search-i18n} + +다국어 검색을 사용하려면 다음과 같은 구성을 사용해야 합니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + locales: { + ko: { // 기본 로케일을 번역하려면 이것을 `root`로 만드십시오. + translations: { + button: { + buttonText: '검색', + buttonAriaLabel: '검색' + }, + modal: { + displayDetails: '상세 목록 표시', + resetButtonTitle: '검색 지우기', + backButtonTitle: '검색 닫기', + noResultsText: '결과를 찾을 수 없습니다', + footer: { + selectText: '선택', + selectKeyAriaLabel: '선택하기', + navigateText: '탐색', + navigateUpKeyAriaLabel: '위로', + navigateDownKeyAriaLabel: '아래로', + closeText: '닫기', + closeKeyAriaLabel: 'esc' + } + } + } + } + } + } + } + } +}) +``` + +### MiniSearch 옵션 {#mini-search-options} + +MiniSearch를 다음과 같이 구성할 수 있습니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + miniSearch: { + /** + * @type {Pick} + */ + options: { + /* ... */ + }, + /** + * @type {import('minisearch').SearchOptions} + * @default + * { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } } + */ + searchOptions: { + /* ... */ + } + } + } + } + } +}) +``` + +더 자세한 내용은 [MiniSearch 문서](https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html)를 참고하세요. + +### 커스텀 컨텐츠 렌더러 {#custom-content-renderer} + +마크다운 컨텐츠를 인덱싱하기 전에 렌더링하는 데 사용되는 함수를 커스터마이징할 수 있습니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + /** + * @param {string} src + * @param {import('vitepress').MarkdownEnv} env + * @param {import('markdown-it')} md + */ + _render(src, env, md) { + // return html string + } + } + } + } +}) +``` + +이 함수는 클라이언트 사이드 사이트 데이터에서 제거되므로, Node.js API를 사용할 수 있습니다. + +#### 예제: 검색에서 페이지 제외 {#example-excluding-pages-from-search} + +페이지의 전문에 `search: false`를 추가하여 검색에서 해당 페이지를 제외할 수 있습니다. 또는: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + _render(src, env, md) { + const html = md.render(src, env) + if (env.frontmatter?.search === false) return '' + if (env.relativePath.startsWith('some/path')) return '' + return html + } + } + } + } +}) +``` + +::: warning 참고 +커스텀 `_render` 함수가 제공된 경우, `search: false` 전문을 직접 처리해야 합니다. 또한, `md.render`가 호출되기 전에 `env` 객체가 완전히 채워지지 않으므로, `frontmatter`와 같은 선택적 `env` 프로퍼티에 대한 검사는 그 이후에 수행해야 합니다. +::: + +#### 예제: 콘텐츠 변환 - 앵커 추가 {#example-transforming-content-adding-anchors} + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + _render(src, env, md) { + const html = md.render(src, env) + if (env.frontmatter?.title) + return md.render(`# ${env.frontmatter.title}`) + html + return html + } + } + } + } +}) +``` + +## Algolia 검색 {#algolia-search} + +VitePress는 [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch)를 사용한 문서 사이트 검색 기능을 지원합니다. 시작 가이드를 참고하세요. `.vitepress/config.ts`에서 이 기능을 사용하려면 최소한 다음 구성을 제공해야 합니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...' + } + } + } +}) +``` + +### i18n {#algolia-search-i18n} + +다국어 검색을 사용하려면 다음과 같이 구성해야 합니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + locales: { + ko: { + placeholder: '문서 검색', + translations: { + button: { + buttonText: '검색', + buttonAriaLabel: '검색' + }, + modal: { + searchBox: { + resetButtonTitle: '검색 지우기', + resetButtonAriaLabel: '검색 지우기', + cancelButtonText: '취소', + cancelButtonAriaLabel: '취소' + }, + startScreen: { + recentSearchesTitle: '검색 기록', + noRecentSearchesText: '최근 검색 없음', + saveRecentSearchButtonTitle: '검색 기록에 저장', + removeRecentSearchButtonTitle: '검색 기록에서 삭제', + favoriteSearchesTitle: '즐겨찾기', + removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제' + }, + errorScreen: { + titleText: '결과를 가져올 수 없습니다', + helpText: '네트워크 연결을 확인하세요' + }, + footer: { + selectText: '선택', + navigateText: '탐색', + closeText: '닫기', + searchByText: '검색 기준' + }, + noResultsScreen: { + noResultsText: '결과를 찾을 수 없습니다', + suggestedQueryText: '새로운 검색을 시도할 수 있습니다', + reportMissingResultsText: '해당 검색어에 대한 결과가 있어야 합니까?', + reportMissingResultsLinkText: '피드백 보내기 클릭' + } + } + } + } + } + } + } + } +}) +``` + +[이 옵션들](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts)은 재작성 할 수 있습니다. 이에 대해 자세히 알고 싶다면 Algolia 공식 문서를 참고하세요. + +### 크롤러 구성 {#crawler-config} + +이 사이트에서 사용하는 예제 구성을 소개합니다: + +```ts +new Crawler({ + appId: '...', + apiKey: '...', + rateLimit: 8, + startUrls: ['https://vitepress.dev/'], + renderJavaScript: false, + sitemaps: [], + exclusionPatterns: [], + ignoreCanonicalTo: false, + discoveryPatterns: ['https://vitepress.dev/**'], + schedule: 'at 05:10 on Saturday', + actions: [ + { + indexName: 'vitepress', + pathsToMatch: ['https://vitepress.dev/**'], + recordExtractor: ({ $, helpers }) => { + return helpers.docsearch({ + recordProps: { + lvl1: '.content h1', + content: '.content p, .content li', + lvl0: { + selectors: '', + defaultValue: 'Documentation' + }, + lvl2: '.content h2', + lvl3: '.content h3', + lvl4: '.content h4', + lvl5: '.content h5' + }, + indexHeadings: true + }) + } + } + ], + initialIndexSettings: { + vitepress: { + attributesForFaceting: ['type', 'lang'], + attributesToRetrieve: ['hierarchy', 'content', 'anchor', 'url'], + attributesToHighlight: ['hierarchy', 'hierarchy_camel', 'content'], + attributesToSnippet: ['content:10'], + camelCaseAttributes: ['hierarchy', 'hierarchy_radio', 'content'], + searchableAttributes: [ + 'unordered(hierarchy_radio_camel.lvl0)', + 'unordered(hierarchy_radio.lvl0)', + 'unordered(hierarchy_radio_camel.lvl1)', + 'unordered(hierarchy_radio.lvl1)', + 'unordered(hierarchy_radio_camel.lvl2)', + 'unordered(hierarchy_radio.lvl2)', + 'unordered(hierarchy_radio_camel.lvl3)', + 'unordered(hierarchy_radio.lvl3)', + 'unordered(hierarchy_radio_camel.lvl4)', + 'unordered(hierarchy_radio.lvl4)', + 'unordered(hierarchy_radio_camel.lvl5)', + 'unordered(hierarchy_radio.lvl5)', + 'unordered(hierarchy_radio_camel.lvl6)', + 'unordered(hierarchy_radio.lvl6)', + 'unordered(hierarchy_camel.lvl0)', + 'unordered(hierarchy.lvl0)', + 'unordered(hierarchy_camel.lvl1)', + 'unordered(hierarchy.lvl1)', + 'unordered(hierarchy_camel.lvl2)', + 'unordered(hierarchy.lvl2)', + 'unordered(hierarchy_camel.lvl3)', + 'unordered(hierarchy.lvl3)', + 'unordered(hierarchy_camel.lvl4)', + 'unordered(hierarchy.lvl4)', + 'unordered(hierarchy_camel.lvl5)', + 'unordered(hierarchy.lvl5)', + 'unordered(hierarchy_camel.lvl6)', + 'unordered(hierarchy.lvl6)', + 'content' + ], + distinct: true, + attributeForDistinct: 'url', + customRanking: [ + 'desc(weight.pageRank)', + 'desc(weight.level)', + 'asc(weight.position)' + ], + ranking: [ + 'words', + 'filters', + 'typo', + 'attribute', + 'proximity', + 'exact', + 'custom' + ], + highlightPreTag: '', + highlightPostTag: '', + minWordSizefor1Typo: 3, + minWordSizefor2Typos: 7, + allowTyposOnNumericTokens: false, + minProximity: 1, + ignorePlurals: true, + advancedSyntax: true, + attributeCriteriaComputedByMinProximity: true, + removeWordsIfNoResults: 'allOptional' + } + } +}) +``` + + diff --git a/docs/ko/reference/default-theme-sidebar.md b/docs/ko/reference/default-theme-sidebar.md new file mode 100644 index 00000000..21e19ccc --- /dev/null +++ b/docs/ko/reference/default-theme-sidebar.md @@ -0,0 +1,215 @@ +# 사이드바 {#sidebar} + +사이드바는 문서의 기본 탐색 블록입니다. [`themeConfig.sidebar`](./default-theme-config#sidebar)에서 사이드바 메뉴를 구성할 수 있습니다. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: '가이드', + items: [ + { text: '소개', link: '/introduction' }, + { text: '시작하기', link: '/getting-started' }, + ... + ] + } + ] + } +} +``` + +## 기본 사용법 {#the-basics} + +사이드바 메뉴의 가장 간단한 형태는 링크 배열을 전달하는 것입니다. 첫 번째 계층 아이템은 사이드바의 "섹션"을 정의합니다. 이 섹션에는 제목인 `text`와 실제 탐색 링크인 `items`가 포함되어야 합니다. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: '섹션 제목 A', + items: [ + { text: '아이템 A', link: '/item-a' }, + { text: '아이템 B', link: '/item-b' }, + ... + ] + }, + { + text: '섹션 제목 B', + items: [ + { text: '아이템 C', link: '/item-c' }, + { text: '아이템 D', link: '/item-d' }, + ... + ] + } + ] + } +} +``` + +각 `link`는 `/`로 시작하는 실제 파일 경로를 지정해야 합니다. 링크 끝에 슬래시를 추가하면 해당 디렉터리의 `index.md`를 보여줍니다. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: '가이드', + items: [ + // 이것은 `/guide/index.md` 페이지를 보여줍니다. + { text: '소개', link: '/guide/' } + ] + } + ] + } +} +``` + +사이드바 아이템을 루트 단계에서 최대 6단계까지 중첩할 수 있습니다. 6단계를 초과하는 중첩 아이템은 무시되며 사이드바에 표시되지 않습니다. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: '1단계', + items: [ + { + text: '2단계', + items: [ + { + text: '3단계', + items: [ + ... + ] + } + ] + } + ] + } + ] + } +} +``` + +## 여러 사이드바 {#multiple-sidebars} + +페이지 경로에 따라 다른 사이드바를 표시할 수 있습니다. 예를 들어 이 사이트처럼 문서의 각 섹션을 "가이드"와 "레퍼런스" 페이지에 따라 별도로 만들고 싶을 수 있습니다. + +이를 위해 먼저 각 섹션 디렉터리로 페이지를 구성합니다: + +``` +. +├─ guide/ +│ ├─ index.md +│ ├─ one.md +│ └─ two.md +└─ config/ + ├─ index.md + ├─ three.md + └─ four.md +``` + +그런 다음 각 섹션에 대한 사이드바를 정의하도록 구성 파일을 업데이트합니다. 이런 경우에는 배열 대신 객체를 전달해야 합니다. + +```js +export default { + themeConfig: { + sidebar: { + // 이 사이드바는 유저가 + // `guide` 디렉토리에 있을 때 표시됩니다. + '/guide/': [ + { + text: '가이드', + items: [ + { text: '개요', link: '/guide/' }, + { text: '하나', link: '/guide/one' }, + { text: '둘', link: '/guide/two' } + ] + } + ], + + // 이 사이드바는 유저가 + // `config` 디렉토리에 있을 때 표시됩니다. + '/config/': [ + { + text: '설정', + items: [ + { text: '개요', link: '/config/' }, + { text: '셋', link: '/config/three' }, + { text: '넷', link: '/config/four' } + ] + } + ] + } + } +} +``` + +## 접을 수 있는 사이드바 그룹 {#collapsible-sidebar-groups} + +사이드바 그룹에 `collapsed` 옵션을 추가하면 각 섹션을 접거나 펼칠 수 있는 토글 버튼이 표시됩니다. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: '섹션 제목 A', + collapsed: false, + items: [...] + } + ] + } +} +``` + +모든 섹션은 기본적으로 "열림" 상태입니다. 초기 페이지 로드 시 "닫힘" 상태로 두려면 `collapsed` 옵션을 `true`로 설정합니다. + +```js +export default { + themeConfig: { + sidebar: [ + { + text: '섹션 제목 A', + collapsed: true, + items: [...] + } + ] + } +} +``` + +## `useSidebar` + +사이드바 관련 데이터를 반환합니다. 반환된 객체는 다음과 같은 타입을 가집니다: + +```ts +export interface DocSidebar { + isOpen: Ref + sidebar: ComputedRef + sidebarGroups: ComputedRef + hasSidebar: ComputedRef + hasAside: ComputedRef + leftAside: ComputedRef + isSidebarEnabled: ComputedRef + open: () => void + close: () => void + toggle: () => void +} +``` + +**예제:** + +```vue + + + +``` diff --git a/docs/ko/reference/default-theme-team-page.md b/docs/ko/reference/default-theme-team-page.md new file mode 100644 index 00000000..2123f349 --- /dev/null +++ b/docs/ko/reference/default-theme-team-page.md @@ -0,0 +1,258 @@ + + +# 팀 페이지 {#team-page} + +팀을 소개하고자 할 때, 팀 컴포넌트를 사용하여 팀 페이지를 구성할 수 있습니다. 이 컴포넌트를 사용하는 방법은 두 가지가 있습니다. 하나는 문서 페이지에 포함시키는 방법이고, 다른 하나는 전체 팀 페이지를 만드는 방법입니다. + +## 페이지에서 팀 구성원 보여주기 {#show-team-members-in-a-page} + +`vitepress/theme`에서 제공되는 `` 컴포넌트를 사용하여, 어떤 페이지에서도 팀 구성원 목록을 표시할 수 있습니다. + +```html + + +# Our Team + +Say hello to our awesome team. + + +``` + +위 코드는 카드 형태의 엘리먼트로 팀 구성원을 표시합니다. 아래와 비슷한 형태로 표시됩니다. + + + +`` 컴포넌트는 `small`과 `medium` 두 가지 크기로 제공됩니다. 개인의 선호도에 따라 선택할 수 있지만, 일반적으로 `small` 사이즈가 문서 페이지에 더 적합합니다. 또한, 각 구성원에 "설명"이나 "후원" 버튼과 같은 프로퍼티를 추가할 수도 있습니다. 자세한 내용은 [``](#vpteammembers)에서 확인할 수 있습니다. + +문서 페이지에 팀 구성원을 포함시키는 것은 전용 팀 페이지를 만드는 것이 과할 수 있는 소규모 팀이나, 문서의 맥락에 따라 일부 구성원을 소개할 때 좋습니다. + +만약 많은 수의 구성원이 있거나, 팀 구성원을 보여줄 더 많은 공간이 필요하다면, [전체 팀 페이지 만들기](#create-a-full-team-page)를 고려해 보세요. + +## 전체 팀 페이지 만들기 {#create-a-full-team-page} + +팀 구성원을 문서 페이지에 추가하는 대신, 전체 팀 페이지를 만들어 [홈 페이지](./default-theme-home-page)를 커스텀하는 것처럼 팀 페이지를 만들 수도 있습니다. + +팀 페이지를 만들려면, 먼저 새로운 마크다운 파일을 생성하세요. 파일 이름은 중요하지 않지만, 여기서는 `team.md`라고 부르겠습니다. 이 파일에서 전문 옵션에 `layout: page`를 설정한 후, `TeamPage` 컴포넌트를 사용하여 페이지 구조를 구성합니다. + +```html +--- +layout: page +--- + + + + + + + + + +``` + +전체 팀 페이지를 만들 때는 모든 컴포넌트를 `` 컴포넌트로 감싸야 합니다. 이 컴포넌트는 중첩된 팀 관련 컴포넌트들이 적절한 레이아웃 구조와 간격을 갖도록 합니다. + +`` 컴포넌트는 페이지 제목 섹션을 추가합니다. 제목은 `

` 헤딩으로 표시됩니다. `#title`과 `#lead` 슬롯을 사용하여 팀에 대한 설명을 작성할 수 있습니다. + +`` 컴포넌트는 문서 페이지에서 사용할 때와 동일하게 작동하며, 팀 구성원 목록을 표시합니다. + +### 팀 구성원을 구분하기 위한 섹션 추가 {#add-sections-to-divide-team-members} + +팀 페이지에 "섹션"을 추가할 수도 있습니다. 예를 들어, 핵심 팀 구성원과 커뮤니티 파트너와 같은 다양한 유형의 팀 구성원이 있을 수 있습니다. 이 구성원들을 섹션으로 나누어 각 그룹의 역할을 더 잘 설명할 수 있습니다. + +이를 위해 이전에 만든 `team.md` 파일에 `` 컴포넌트를 추가하세요. + +```html +--- +layout: page +--- + + + + + + + + + + + + + + +``` + +`` 컴포넌트는 `VPTeamPageTitle` 컴포넌트처럼 `#title`과 `#lead` 슬롯을 가질 수 있으며, 팀 구성원을 표시하기 위한 `#members` 슬롯도 있습니다. + +`#members` 슬롯 내부에는 `` 컴포넌트를 추가해야 합니다. + +## `` + +`` 컴포넌트는 주어진 팀 구성원 목록을 표시합니다. + +```html + +``` + +```ts +interface Props { + // 각 구성원 사이즈. 기본값: `medium` + size?: 'small' | 'medium' + + // 표시할 구성원 목록. + members: TeamMember[] +} + +interface TeamMember { + // 구성원 아바타 이미지. + avatar: string + + // 구성원 이름. + name: string + + // 구성원 이름 아래에 표시될 직함. + // 예: 개발자, 소프트웨어 엔지니어 등 + title?: string + + // 구성원이 속한 조직. + org?: string + + // 조직의 URL. + orgLink?: string + + // 구성원에 대한 설명. + desc?: string + + // 소셜 링크. 예: GitHub, Twitter 등. + // 소셜 링크 객체를 전달해야 함. + // 참고: https://vitepress.dev/ko/reference/default-theme-config.html#sociallinks + links?: SocialLink[] + + // 구성원의 후원 페이지 URL. + sponsor?: string + + // 후원 링크 텍스트. 기본값: 'Sponsor' + actionText?: string +} +``` + +## `` + +전체 팀 페이지를 만들 때 사용하는 루트 컴포넌트입니다. 단일 슬롯만 허용하며, 전달된 모든 팀 관련 컴포넌트에 스타일을 적용합니다. + +## `` + +페이지의 "제목" 섹션을 추가합니다. `` 아래 맨 처음에 사용하는 것이 가장 좋습니다. `#title`과 `#lead` 슬롯이 있습니다. + +```html + + + + + + +``` + +## `` + +팀 페이지 내에서 "섹션"을 생성합니다. `#title`, `#lead`, `#members` 슬롯이 있습니다. `` 안에 원하는 만큼 섹션을 추가할 수 있습니다. + +```html + + ... + + + + + + +``` diff --git a/docs/ko/reference/frontmatter-config.md b/docs/ko/reference/frontmatter-config.md new file mode 100644 index 00000000..b10768a4 --- /dev/null +++ b/docs/ko/reference/frontmatter-config.md @@ -0,0 +1,221 @@ +--- +outline: deep +--- + +# 전문 구성 {#frontmatter-config} + +전문은 페이지 기반 구성을 가능하게 합니다. 각 마크다운 파일에서 전문 구성을 사용하여 사이트 수준 또는 테마 수준의 구성 옵션을 재정의할 수 있습니다. 또한, 전문에서만 정의할 수 있는 구성 옵션도 있습니다. + +사용 예: + +```md +--- +title: Docs with VitePress +editLink: true +--- +``` + +Vue 표현식에서 `$frontmatter` 전역 변수를 통해 전문 데이터에 접근할 수 있습니다: + +```md +{{ $frontmatter.title }} +``` + +## title + +- 타입: `string` + +페이지의 제목입니다. [config.title](./site-config#title)과 동일하며, 사이트 레벨의 구성을 재정의합니다. + +```yaml +--- +title: VitePress +--- +``` + +## titleTemplate + +- 타입: `string | boolean` + +제목의 접미사입니다. [config.titleTemplate](./site-config#titletemplate)와 동일하며, 사이트 레벨의 구성을 재정의합니다. + +```yaml +--- +title: VitePress +titleTemplate: Vite & Vue powered static site generator +--- +``` + +## description + +- 타입: `string` + +페이지의 설명입니다. [config.description](./site-config#description)과 동일하며, 사이트 레벨의 구성을 재정의합니다. + +```yaml +--- +description: VitePress +--- +``` + +## head + +- 타입: `HeadConfig[]` + +현재 페이지에 삽입할 추가 head 태그를 지정합니다. 사이트 수준 구성에 의해 삽입된 head 태그 뒤에 추가됩니다. + +```yaml +--- +head: + - - meta + - name: description + content: hello + - - meta + - name: keywords + content: super duper SEO +--- +``` + +```ts +type HeadConfig = + | [string, Record] + | [string, Record, string] +``` + +## 기본 테마 전용 {#default-theme-only} + +다음 전문 옵션은 기본 테마를 사용할 때만 적용됩니다. + +### layout + +- 타입: `doc | home | page` +- 기본값: `doc` + +페이지의 레이아웃을 결정합니다. + +- `doc` - 마크다운 컨텐츠에 기본 문서 스타일을 적용합니다. +- `home` - "홈 페이지"를 위한 특별 레이아웃입니다. 아름다운 랜딩 페이지를 빠르게 만들기 위해 `hero` 및 `features`와 같은 옵션을 추가할 수 있습니다. +- `page` - `doc`과 유사하게 작동하지만 콘텐츠에 스타일을 적용하지 않습니다. 완전히 커스텀 페이지를 만들 때 유용합니다. + +```yaml +--- +layout: doc +--- +``` + +### hero + +`layout`이 `home`으로 설정된 경우, 홈 히어로 섹션의 내용을 정의합니다. 자세한 내용은 [기본 테마: 홈 페이지](./default-theme-home-page)에서 확인할 수 있습니다. + +### features + +`layout`이 `home`으로 설정된 경우, 기능 섹션에 표시할 항목을 정의합니다. 자세한 내용은 [기본 테마: 홈 페이지](./default-theme-home-page)에서 확인할 수 있습니다. + +### navbar + +- 타입: `boolean` +- 기본값: `true` + +[네비게이션 바](./default-theme-nav)를 표시할지 여부를 설정합니다. + +```yaml +--- +navbar: false +--- +``` + +### sidebar + +- 타입: `boolean` +- 기본값: `true` + +[사이드바](./default-theme-sidebar)를 표시할지 여부를 설정합니다. + +```yaml +--- +sidebar: false +--- +``` + +### aside + +- 타입: `boolean | 'left'` +- 기본값: `true` + +`doc` 레이아웃에서 어사이드(aside) 컴포넌트의 위치를 정의합니다. + +이 값을 `false`로 설정하면 어사이드 컨테이너가 렌더링되지 않습니다.\ +이 값을 `true`로 설정하면 어사이드를 오른쪽에 렌더링합니다.\ +이 값을 `'left'`로 설정하면 어사이드를 왼쪽에 렌더링합니다. + +```yaml +--- +aside: false +--- +``` + +### outline + +- 타입: `number | [number, number] | 'deep' | false` +- 기본값: `2` + +페이지에 표시할 아웃라인(개요) 헤더의 레벨을 설정합니다. [config.themeConfig.outline.level](./default-theme-config#outline)과 동일하며, 사이트 수준 구성에서 설정된 값을 재정의합니다. + +### lastUpdated + +- 타입: `boolean | Date` +- 기본값: `true` + +현재 페이지의 푸터에 [마지막 업데이트 날짜](./default-theme-last-updated) 텍스트를 표시할지 여부를 설정합니다. 날짜/시간이 지정되면 마지막 git 수정 타임스탬프 대신 해당 날짜/시간이 표시됩니다. + +```yaml +--- +lastUpdated: false +--- +``` + +### editLink + +- 타입: `boolean` +- 기본값: `true` + +현재 페이지의 푸터에 [편집 링크](./default-theme-edit-link)를 표시할지 여부를 설정합니다. + +```yaml +--- +editLink: false +--- +``` + +### footer + +- 타입: `boolean` +- 기본값: `true` + +[푸터](./default-theme-footer)를 표시할지 여부를 설정합니다. + +```yaml +--- +footer: false +--- +``` + +### pageClass + +- 타입: `string` + +페이지에 추가할 클래스 입니다. + +```yaml +--- +pageClass: custom-page-class +--- +``` + +그런 다음 `.vitepress/theme/custom.css` 파일에서 이 페이지의 스타일을 커스텀 할 수 있습니다: + +```css +.custom-page-class { + /* 페이지별 스타일 */ +} +``` diff --git a/docs/ko/reference/runtime-api.md b/docs/ko/reference/runtime-api.md new file mode 100644 index 00000000..a483ea2f --- /dev/null +++ b/docs/ko/reference/runtime-api.md @@ -0,0 +1,169 @@ +# 런타임 API {#runtime-api} + +VitePress는 애플리케이션 데이터를 액세스할 수 있는 여러 내장 API를 제공합니다. 그리고 전역적으로 사용할 수 있는 몇 가지 내장 컴포넌트도 제공합니다. + +헬퍼 메서드는 `vitepress`에서 전역적으로 사용할 수 있으며, 주로 커스텀 테마의 Vue 컴포넌트에서 사용됩니다. 또한 마크다운 파일이 Vue [단일 파일 컴포넌트](https://vuejs.org/guide/scaling-up/sfc.html)로 컴파일되기 때문에 `.md` 페이지 내에서도 사용할 수 있습니다. + +`use*`로 시작하는 메서드는 [Vue 3 Composition API](https://vuejs.org/guide/introduction.html#composition-api) 함수("컴포저블")를 나타내며, 이는 `setup()` 또는 ` + + +``` + +## `useRoute` + +다음과 같은 타입으로 현재 라우트 객체를 반환합니다: + +```ts +interface Route { + path: string + data: PageData + component: Component | null +} +``` + +## `useRouter` + +프로그래밍 방식으로 다른 페이지로 이동할 수 있도록 VitePress 라우터 인스턴스를 반환합니다. + +```ts +interface Router { + /** + * 현재 route. + */ + route: Route + /** + * 새 URL로 이동. + */ + go: (to?: string) => Promise + /** + * 라우트가 변경되기 전에 호출. 탐색을 취소하려면 `false`를 반환. + */ + onBeforeRouteChange?: (to: string) => Awaitable + /** + * 페이지 컴포넌트가 로드되기 전(히스토리 상태가 업데이트된 후)에 호출. + * 탐색을 취소하려면 `false`를 반환. + */ + onBeforePageLoad?: (to: string) => Awaitable + /** + * 라우트가 변경된 후 호출. + */ + onAfterRouteChanged?: (to: string) => Awaitable +} +``` + +## `withBase` + +- **타입**: `(path: string) => string` + +구성된 [`base`](./site-config#base)를 지정된 URL 경로에 추가합니다. [Base URL](../guide/asset-handling#base-url)을 참고하세요. + +## `` + +`` 컴포넌트는 렌더링된 마크다운 내용을 표시합니다. [커스텀 테마를 만들 때](../guide/custom-theme) 유용합니다. + +```vue + +``` + +## `` + +`` 컴포넌트는 클라이언트 측에서만 슬롯을 렌더링합니다. + +VitePress 애플리케이션은 정적 빌드를 생성할 때 Node.js에서 서버 렌더링되므로 모든 Vue 사용은 범용 코드 요구 사항을 준수해야 합니다. 간단히 말해서, 브라우저 / DOM API는 반드시 beforeMount 또는 mounted 훅에서만 접근해야 합니다. + +SSR 친화적이지 않은(예: 커스텀 디렉티브를 포함하는) 컴포넌트를 사용하는 경우, 이를 `ClientOnly` 컴포넌트 내부에 래핑할 수 있습니다. + +```vue-html + + + +``` + +- 참고: [SSR 호환성](../guide/ssr-compat) + +## `$frontmatter` + +Vue 표현식에서 현재 페이지의 [전문](../guide/frontmatter) 데이터에 직접 접근합니다. + +```md +--- +title: Hello +--- + +# {{ $frontmatter.title }} +``` + +## `$params` + +Vue 표현식에서 현재 페이지의 [동적 라우트 파라미터](../guide/routing#dynamic-routes)에 직접 접근합니다. + +```md +- package name: {{ $params.pkg }} +- version: {{ $params.version }} +``` diff --git a/docs/ko/reference/site-config.md b/docs/ko/reference/site-config.md new file mode 100644 index 00000000..25dbcc01 --- /dev/null +++ b/docs/ko/reference/site-config.md @@ -0,0 +1,722 @@ +--- +outline: deep +--- + +# 사이트 구성 {#site-config} + +사이트 구성(config)은 사이트의 전역 설정을 정의할 수 있는 곳입니다. 애플리케이션 구성 옵션은 사용 중인 테마와 상관없이 모든 VitePress 사이트에 적용되는 설정을 정의합니다. 예를 들어 기본 디렉터리나 사이트의 제목 등이 있습니다. + +## 개요 {#overview} + +### 구성 분석 {#config-resolution} + +구성 파일은 항상 `/.vitepress/config.[ext]`에서 처리됩니다. 여기서 ``는 VitePress [프로젝트 루트](../guide/routing#root-and-source-directory)를 의미하며, `[ext]`는 지원되는 파일 확장자 중 하나입니다. TypeScript는 기본적으로 지원됩니다. 지원되는 확장자에는 `.js`, `.ts`, `.mjs`, `.mts`가 포함됩니다. + +구성 파일에서는 ES 모듈 구문을 사용하는 것이 권장됩니다. 구성 파일은 객체를 "default export"해야 합니다: + +```ts +export default { + // 애플리케이션 레벨의 구성 옵션 + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue powered static site generator.', + ... +} +``` + +::: details 동적(비동기) 구성 + +구성을 동적으로 생성해야 하는 경우, 함수를 "default export" 할 수 있습니다. 예: + +```ts +import { defineConfig } from 'vitepress' + +export default async () => { + const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + + return defineConfig({ + // 애플리케이션 레벨의 구성 옵션 + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue powered static site generator.', + + // 테마 레벨의 구성 옵션 + themeConfig: { + sidebar: [ + ...posts.map((post) => ({ + text: post.name, + link: `/posts/${post.name}` + })) + ] + } + }) +} +``` + +최상위 수준의 `await`도 사용할 수 있습니다. 예: + +```ts +import { defineConfig } from 'vitepress' + +const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + +export default defineConfig({ + // 앱 레벨 설정 옵션 + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue를 활용한 정적 사이트 생성기.', + + // 테마 레벨 설정 옵션 + themeConfig: { + sidebar: [ + ...posts.map((post) => ({ + text: post.name, + link: `/posts/${post.name}` + })) + ] + } +}) +``` + +::: + +### 구성 인텔리센스 {#config-intellisense} + +`defineConfig` 헬퍼를 사용하면 구성 옵션에 대해 TypeScript 기반의 인텔리센스(자동완성)를 제공받을 수 있습니다. IDE가 이를 지원하는 경우, JavaScript와 TypeScript 모두에서 작동합니다. + +```js +import { defineConfig } from 'vitepress' + +export default defineConfig({ + // ... +}) +``` + +### 타입이 지정된 테마 구성 {#typed-theme-config} + +기본적으로 `defineConfig` 헬퍼는 기본 테마에서 테마 구성 타입을 예측합니다: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + // 타입은 `DefaultTheme.Config` + } +}) +``` + +커스텀 테마를 사용하고 테마 구성에 대한 타입 검사를 원한다면, `defineConfigWithTheme`를 사용하고 제네릭 인수를 통해 커스텀 테마의 구성 타입을 전달해야 합니다: + +```ts +import { defineConfigWithTheme } from 'vitepress' +import type { ThemeConfig } from 'your-theme' + +export default defineConfigWithTheme({ + themeConfig: { + // 타입은 `ThemeConfig` + } +}) +``` + +### Vite, Vue, Markdown 설정 {#vite-vue-markdown-config} + +- **Vite** + + VitePress 구성에서 [vite](#vite) 옵션을 사용하여 기본 Vite 인스턴스를 구성할 수 있습니다. 별도의 Vite 구성 파일을 만들 필요는 없습니다. + +- **Vue** + + VitePress는 이미 Vite의 공식 Vue 플러그인([@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue))을 포함하고 있습니다. VitePress 구성에서 [vue](#vue) 옵션을 사용하여 해당 옵션을 구성할 수 있습니다. + +- **Markdown** + + [Markdown-It](https://github.com/markdown-it/markdown-it) 인스턴스를 VitePress 구성에서 [markdown](#markdown) 옵션을 사용하여 구성할 수 있습니다. + +## 사이트 메타데이터 {#site-metadata} + +### title + +- 타입: `string` +- 기본값: `VitePress` +- [전문](./frontmatter-config#title)을 통해 페이지별로 재정의 가능 + +사이트의 제목입니다. 기본 테마를 사용할 경우, 이는 내비게이션 바에 표시됩니다. + +[`titleTemplate`](#titletemplate)이 정의되지 않은 경우, 모든 개별 페이지 제목의 기본 접미사로 사용됩니다. 개별 페이지의 최종 제목은 첫 번째 `

` 헤더의 텍스트 콘텐츠와 전역 `title`을 접미사로 결합한 것입니다. 예를 들어 다음 구성과 페이지 콘텐츠가 있을 경우: + +```ts +export default { + title: 'My Awesome Site' +} +``` + +```md +# Hello +``` + +페이지의 제목은 `Hello | My Awesome Site`가 됩니다. + +### titleTemplate + +- 타입: `string | boolean` +- [전문](./frontmatter-config#titletemplate)을 통해 페이지별로 재정의 가능 + +각 페이지의 제목 접미사 또는 전체 제목을 커스터마이징할 수 있습니다. 예를 들어: + +```ts +export default { + title: 'My Awesome Site', + titleTemplate: 'Custom Suffix' +} +``` + +```md +# Hello +``` + +페이지의 제목은 `Hello | Custom Suffix`가 됩니다. + +제목이 렌더링되는 방식을 완전히 커스터마이징하려면 `titleTemplate`에서 `:title` 심볼을 사용할 수 있습니다: + +```ts +export default { + titleTemplate: ':title - Custom Suffix' +} +``` + +여기서 `:title`은 페이지의 첫 번째 `

` 헤더에서 추론된 텍스트로 대체됩니다. 이전 예제 페이지의 제목은 `Hello - Custom Suffix`가 됩니다. + +이 옵션을 `false`로 설정하여 제목 접미사를 비활성화할 수 있습니다. + +### description + +- 타입: `string` +- 기본값: `A VitePress site` +- [전문](./frontmatter-config#description)을 통해 페이지별로 재정의 가능 + +사이트의 설명입니다. 이는 페이지 HTML의 `` 태그로 렌더링됩니다. + +```ts +export default { + description: 'A VitePress site' +} +``` + +### head + +- 타입: `HeadConfig[]` +- 기본값: `[]` +- [전문](./frontmatter-config#head)을 통해 페이지별로 추가 가능 + +페이지 HTML의 `` 태그에 렌더링할 추가 엘리먼트입니다. 추가한 태그는 VitePress 태그 뒤 ~ 닫는 `head` 태그 앞에 렌더링됩니다. + +```ts +type HeadConfig = + | [string, Record] + | [string, Record, string] +``` + +#### 예제: 파비콘 추가 {#example-adding-a-favicon} + +```ts +export default { + head: [['link', { rel: 'icon', href: '/favicon.ico' }]] +} // favicon.ico를 public 디렉토리에 배치하거나 base가 설정된 경우, + // /base/favicon.ico를 사용하세요. +/* 다음과 같이 랜더링: + +*/ +``` + +#### 예제: Google 폰트 추가 {#example-adding-google-fonts} + +```ts +export default { + head: [ + [ + 'link', + { rel: 'preconnect', href: 'https://fonts.googleapis.com' } + ], + [ + 'link', + { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' } + ], + [ + 'link', + { href: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap', rel: 'stylesheet' } + ] + ] +} + +/* 다음과 같이 랜더링: + + + +*/ +``` + +#### 예제: 서비스 워커 등록 {#example-registering-a-service-worker} + +```ts +export default { + head: [ + [ + 'script', + { id: 'register-sw' }, + `;(() => { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js') + } + })()` + ] + ] +} + +/* 다음과 같이 랜더링: + +*/ +``` + +#### 예제: Google Analytics 사용 {#example-using-google-analytics} + +```ts +export default { + head: [ + [ + 'script', + { async: '', src: 'https://www.googletagmanager.com/gtag/js?id=TAG_ID' } + ], + [ + 'script', + {}, + `window.dataLayer = window.dataLayer || []; + function gtag(){dataLayer.push(arguments);} + gtag('js', new Date()); + gtag('config', 'TAG_ID');` + ] + ] +} + +/* 다음과 같이 랜더링: + + +*/ +``` + +### lang + +- 타입: `string` +- 기본값: `en-US` + +사이트의 언어 어트리뷰트입니다. 이는 페이지 HTML의 `` 태그로 렌더링됩니다. + +```ts +export default { + lang: 'en-US' +} +``` + +### base + +- 타입: `string` +- 기본값: `/` + +사이트가 배포될 기본 URL입니다. 예를 들어 GitHub Pages와 같이 서브 경로에 사이트를 배포하려는 경우 이것을 설정해야 합니다. `https://foo.github.io/bar/` 에 사이트를 배포하려면 `'/bar/'`로 설정해야 합니다. 항상 슬래시로 시작하고 끝나야 합니다. + +이것은 다른 옵션에서 `/`로 시작하는 모든 URL에 자동으로 추가되므로, 한 번만 지정하면 됩니다. + +```ts +export default { + base: '/base/' +} +``` + +## 라우팅 {#routing} + +### cleanUrls + +- 타입: `boolean` +- 기본값: `false` + +`true`로 설정하면 VitePress는 URL에서 `.html`을 제거합니다. [간결한 URL 생성](../guide/routing#generating-clean-url)을 참고하세요. + +::: warning 서버 지원 필요 +이를 활성화하려면 호스팅 플랫폼에서 추가 구성이 필요할 수 있습니다. 서버가 `/foo`를 방문할 때 **리디렉션 없이** `/foo.html`을 제공할 수 있어야 합니다. +::: + +### rewrites + +- 타입: `Record` + +커스텀 디렉터리와 URL 매핑을 정의합니다. 자세한 내용은 [라우팅: 라우트 재작성](../guide/routing#route-rewrites)을 참고하세요. + +```ts +export default { + rewrites: { + 'source/:page': 'destination/:page' + } +} +``` + +## 빌드 {#build} + +### srcDir + +- 타입: `string` +- 기본값: `.` + +마크다운 페이지가 저장되는 디렉터리입니다. 프로젝트 루트에 상대적입니다. 또한 [루트와 소스 디렉터리](../guide/routing#root-and-source-directory)를 참고하세요. + +```ts +export default { + srcDir: './src' +} +``` + +### srcExclude + +- 타입: `string` +- 기본값: `undefined` + +소스 컨텐츠에서 제외해야 하는 마크다운 파일을 매칭하기 위한 [glob 패턴](https://github.com/mrmlnc/fast-glob#pattern-syntax)입니다. + +```ts +export default { + srcExclude: ['**/README.md', '**/TODO.md'] +} +``` + +### outDir + +- 타입: `string` +- 기본값: `./.vitepress/dist` + +사이트의 빌드 결과물 위치입니다. [프로젝트 루트](../guide/routing#root-and-source-directory)에 상대적입니다. + +```ts +export default { + outDir: '../public' +} +``` + +### assetsDir + +- 타입: `string` +- 기본값: `assets` + +생성된 에셋을 포함할 디렉터리를 지정합니다. 경로는 [`outDir`](#outdir) 내에 있어야 하며, 그것을 기준으로 처리됩니다. + +```ts +export default { + assetsDir: 'static' +} +``` + +### cacheDir + +- 타입: `string` +- 기본값: `./.vitepress/cache` + +캐시 파일을 위한 디렉터리입니다. [프로젝트 루트](../guide/routing#root-and-source-directory)에 상대적입니다. [cacheDir](https://vitejs.dev/config/shared-options.html#cachedir)을 참고하세요. + +```ts +export default { + cacheDir: './.vitepress/.vite' +} +``` + +### ignoreDeadLinks + +- 타입: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- 기본값: `false` + +`true`로 설정하면, 빌드 시 죽은 링크로 인해 실패하지 않습니다. + +`'localhostLinks'`로 설정하면, 죽은 링크가 있으면 빌드에 실패하지만 `localhost` 링크는 확인하지 않습니다. + +```ts +export default { + ignoreDeadLinks: true +} +``` + +정확히 일치하는 URL 문자열, 정규 표현식 패턴, 커스텀 필터 함수로 구성된 배열도 가능합니다. + +```ts +export default { + ignoreDeadLinks: [ + // "/playground"과 정확히 일치하는 url 무시 + '/playground', + // 모든 localhost 링크 무시 + /^https?:\/\/localhost/, + // 모든 "/repl/" 포함 링크 무시 + /\/repl\//, + // 커스텀 함수, "ignore"를 포함한 모든 링크 무시 + (url) => { + return url.toLowerCase().includes('ignore') + } + ] +} +``` + +### metaChunk + +- 타입: `boolean` +- 기본값: `false` + +`true`로 설정하면 페이지 메타데이터를 초기 HTML에 인라인으로 삽입하는 대신 별도의 JavaScript 청크로 추출합니다. 이렇게 하면 각 페이지의 HTML 페이로드가 작아지고 페이지 메타데이터를 캐시할 수 있어, 사이트에 많은 페이지가 있을 때 서버 대역폭을 줄일 수 있습니다. + +### mpa + +- 타입: `boolean` +- 기본값: `false` + +`true`로 설정하면 프로덕션 애플리케이션이 [MPA 모드](../guide/mpa-mode)로 빌드됩니다. MPA 모드는 기본적으로 0kb JavaScript를 제공하지만, 클라이언트 사이드 탐색을 비활성화하고 상호작용을 위한 명시적인 옵트인을 필요로 합니다. + +## 테마 {#theming} + +### appearance + +- 타입: `boolean | 'dark' | 'force-dark' | 'force-auto' | import('@vueuse/core').UseDarkOptions` +- 기본값: `true` + +다크 모드를 활성화 여부를 설정합니다 (`.dark` 클래스를 `` 엘리먼트에 추가). + +- `true`: 기본 테마는 유저의 선호 색상 설정에 따라 결정됩니다. +- `dark`: 유저가 수동으로 변경하지 않는 한 기본 테마는 다크 모드가 됩니다. +- `false`: 유저는 테마를 전환할 수 없습니다. +- `'force-dark'`: 테마는 항상 다크 모드가 되며 유저는 이를 전환할 수 없습니다. +- `'force-auto'`: 테마는 항상 유저의 선호 색상 설정에 따라 결정되며 유저는 이를 전환할 수 없습니다. + +이 옵션은 `vitepress-theme-appearance` 키를 사용하여 로컬 스토리지에서 유저 설정을 복원하는 인라인 스크립트를 삽입합니다. 이는 페이지가 렌더링되기 전에 `.dark` 클래스가 적용되어 깜박임을 방지합니다. + +`appearance.initialValue`는 `'dark'` 또는 `undefined`만 가능합니다. Refs 또는 getter는 지원되지 않습니다. + +### lastUpdated + +- 타입: `boolean` +- 기본값: `false` + +각 페이지의 마지막 업데이트 타임스탬프를 Git을 사용하여 가져올지 여부를 설정합니다. 타임스탬프는 각 페이지의 페이지 데이터에 포함되며, [`useData`](./runtime-api#usedata)를 통해 접근할 수 있습니다. + +기본 테마를 사용할 때, 이 옵션을 활성화하면 각 페이지의 마지막 업데이트 시간이 표시됩니다. [`themeConfig.lastUpdatedText`](./default-theme-config#lastupdatedtext) 옵션을 통해 텍스트를 커스터마이징할 수 있습니다. + +## 커스터마이징 {#customization} + +### markdown + +- 타입: `MarkdownOption` + +마크다운 파서 옵션을 구성합니다. VitePress는 파서로 [Markdown-it](https://github.com/markdown-it/markdown-it)을 사용하고, 언어 구문 강조를 위해 [Shiki](https://github.com/shikijs/shiki)를 사용합니다. 이 옵션 내에서 다양한 마크다운 관련 옵션을 전달하여 필요에 맞게 조정할 수 있습니다. + +```js +export default { + markdown: {...} +} +``` + +사용 가능한 모든 옵션에 대해서는 [타입 선언 및 jsdocs](https://github.com/vuejs/vitepress/blob/main/src/node/markdown/markdown.ts)를 참고하세요. + +### vite + +- 타입: `import('vite').UserConfig` + +내부 Vite 개발 서버/번들러에 직접 [Vite 구성](https://vitejs.dev/config/)을 전달합니다. + +```js +export default { + vite: { + // Vite 구성 옵션 + } +} +``` + +### vue + +- 타입: `import('@vitejs/plugin-vue').Options` + +내부 플러그인 인스턴스에 직접 [`@vitejs/plugin-vue` 옵션](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue#options)을 전달합니다. + +```js +export default { + vue: { + // @vitejs/plugin-vue 옵션 + } +} +``` + +## 빌드 훅 {#build-hooks} + +VitePress 빌드 훅은 웹사이트에 새로운 기능과 동작을 추가할 수 있게 합니다: + +- 사이트맵 +- 검색 인덱싱 +- PWA +- 텔레포트 + +### buildEnd + +- 타입: `(siteConfig: SiteConfig) => Awaitable` + +`buildEnd`는 빌드 CLI 훅으로, 빌드(SSG)가 완료된 후 VitePress CLI 프로세스가 종료되기 전에 실행됩니다. + +```ts +export default { + async buildEnd(siteConfig) { + // ... + } +} +``` + +### postRender + +- 타입: `(context: SSGContext) => Awaitable` + +`postRender`는 빌드 훅으로, SSG 렌더링이 완료되었을 때 호출됩니다. 이를 통해 SSG 동안 텔레포트 콘텐츠를 핸들링 할 수 있습니다. + +```ts +export default { + async postRender(context) { + // ... + } +} +``` + +```ts +interface SSGContext { + content: string + teleports?: Record + [key: string]: any +} +``` + +### transformHead + +- 타입: `(context: TransformContext) => Awaitable` + +`transformHead`는 각 페이지를 생성하기 전에 헤드를 변환하는 빌드 훅입니다. VitePress 구성에 정적으로 추가할 수 없는 헤드 항목을 추가할 수 있습니다. 기존 항목과 자동으로 병합되므로 추가 항목만 반환하면 됩니다. + +::: warning +`context` 내부의 어떤 것도 변경하지 마세요. +::: + +```ts +export default { + async transformHead(context) { + // ... + } +} +``` + +```ts +interface TransformContext { + page: string // 예: index.md (srcDir에 상대적) + assets: string[] // js/css가 아닌 모든 에셋을 완전히 처리된 public URL로 표시. + siteConfig: SiteConfig + siteData: SiteData + pageData: PageData + title: string + description: string + head: HeadConfig[] + content: string +} +``` + +이 훅은 사이트를 정적으로 생성할 때만 호출됩니다. 개발 중에는 호출되지 않습니다. 개발 중에 동적 헤드 항목을 추가해야 하는 경우, [`transformPageData`](#transformpagedata) 훅을 대신 사용할 수 있습니다: + +```ts +export default { + transformPageData(pageData) { + pageData.frontmatter.head ??= [] + pageData.frontmatter.head.push([ + 'meta', + { + name: 'og:title', + content: + pageData.frontmatter.layout === 'home' + ? `VitePress` + : `${pageData.title} | VitePress` + } + ]) + } +} +``` + +#### 예제: 표준 URL `` 추가 {#example-adding-a-canonical-url-link} + +```ts +export default { + transformPageData(pageData) { + const canonicalUrl = `https://example.com/${pageData.relativePath}` + .replace(/index\.md$/, '') + .replace(/\.md$/, '.html') + + pageData.frontmatter.head ??= [] + pageData.frontmatter.head.push([ + 'link', + { rel: 'canonical', href: canonicalUrl } + ]) + } +} +``` + +### transformHtml + +- 타입: `(code: string, id: string, context: TransformContext) => Awaitable` + +`transformHtml`은 각 페이지의 내용을 디스크에 저장하기 전에 변환하는 빌드 훅입니다. + +::: warning +`context` 내부의 어떤 것도 변경하지 마세요. HTML 내용을 수정하면 런타임에 하이드레이션 문제가 발생할 수 있습니다. +::: + +```ts +export default { + async transformHtml(code, id, context) { + // ... + } +} +``` + +### transformPageData + +- 타입: `(pageData: PageData, context: TransformPageContext) => Awaitable | { [key: string]: any } | void>` + +`transformPageData`는 각 페이지의 `pageData`를 변환하는 훅입니다. `pageData`를 직접 변경하거나, 변경된 값을 반환하여 페이지 데이터에 병합할 수 있습니다. + +::: warning +`context` 내부의 어떤 것도 변경하지 마세요. 이 훅에서 네트워크 요청이나 이미지 생성과 같은 무거운 연산이 있을 경우 개발 서버의 성능에 영향을 줄 수 있으니 주의하세요. 조건부 로직을 위해 `process.env.NODE_ENV === 'production'`을 확인할 수 있습니다. +::: + +```ts +export default { + async transformPageData(pageData, { siteConfig }) { + pageData.contributors = await getPageContributors(pageData.relativePath) + } + + // 또는 병합할 데이터 반환 + async transformPageData(pageData, { siteConfig }) { + return { + contributors: await getPageContributors(pageData.relativePath) + } + } +} +``` + +```ts +interface TransformPageContext { + siteConfig: SiteConfig +} +``` diff --git a/docs/lunaria.config.json b/docs/lunaria.config.json index 73b7a38a..1de46a38 100644 --- a/docs/lunaria.config.json +++ b/docs/lunaria.config.json @@ -6,7 +6,7 @@ }, "files": [ { - "location": ".vitepress/config/{en,zh,pt,ru}.ts", + "location": ".vitepress/config/{en,zh,pt,ru,es,ko}.ts", "pattern": ".vitepress/config/@lang.ts", "type": "universal" }, @@ -32,6 +32,14 @@ { "label": "Русский", "lang": "ru" + }, + { + "label": "Español", + "lang": "es" + }, + { + "label": "한국어", + "lang": "ko" } ], "outDir": ".vitepress/dist/_translations", diff --git a/docs/package.json b/docs/package.json index 9ef5821a..25c3a0af 100644 --- a/docs/package.json +++ b/docs/package.json @@ -3,14 +3,14 @@ "private": true, "type": "module", "scripts": { - "build": "vitepress build", "dev": "vitepress dev", + "build": "vitepress build", + "preview": "vitepress preview", "lunaria:build": "lunaria build", - "lunaria:open": "open-cli .vitepress/dist/_translations/index.html", - "preview": "vitepress preview" + "lunaria:open": "open-cli .vitepress/dist/_translations/index.html" }, "devDependencies": { - "@lunariajs/core": "^0.0.32", + "@lunariajs/core": "^0.1.1", "markdown-it-mathjax3": "^4.3.2", "open-cli": "^8.0.0", "vitepress": "workspace:*" diff --git a/docs/pt/guide/deploy.md b/docs/pt/guide/deploy.md index ba8b2fd8..e853aa37 100644 --- a/docs/pt/guide/deploy.md +++ b/docs/pt/guide/deploy.md @@ -288,4 +288,4 @@ Consulte [Criar e Implantar um Aplicativo VitePress no Edgio](https://docs.edg.i ### Kinsta Static Site Hosting {#kinsta-static-site-hosting} -Você pode implantar seu site Vitepress em [Kinsta](https://kinsta.com/static-site-hosting/) seguindo estas [instruções](https://kinsta.com/docs/vitepress-static-site-example/). +Você pode implantar seu site VitePress em [Kinsta](https://kinsta.com/static-site-hosting/) seguindo estas [instruções](https://kinsta.com/docs/vitepress-static-site-example/). diff --git a/docs/pt/guide/extending-default-theme.md b/docs/pt/guide/extending-default-theme.md index db68e954..88d32d12 100644 --- a/docs/pt/guide/extending-default-theme.md +++ b/docs/pt/guide/extending-default-theme.md @@ -337,4 +337,4 @@ export default defineConfig({ }) ``` -Para saber o nome exato do componente consulte [nosso código fonte](https://github.com/vuejs/vitepress/tree/main/src/client/theme-default/components). Como os componentes são internos, há uma pequena chance de que o nome deles seja atualizado entre lançamentos secundários. \ No newline at end of file +Para saber o nome exato do componente consulte [nosso código fonte](https://github.com/vuejs/vitepress/tree/main/src/client/theme-default/components). Como os componentes são internos, há uma pequena chance de que o nome deles seja atualizado entre lançamentos secundários. diff --git a/docs/pt/guide/getting-started.md b/docs/pt/guide/getting-started.md index 00715ecf..8d4d4ccb 100644 --- a/docs/pt/guide/getting-started.md +++ b/docs/pt/guide/getting-started.md @@ -29,6 +29,10 @@ $ pnpm add -D vitepress $ yarn add -D vitepress ``` +```sh [yarn (pnp)] +$ yarn add -D vitepress vue +``` + ```sh [bun] $ bun add -D vitepress ``` diff --git a/docs/pt/guide/i18n.md b/docs/pt/guide/i18n.md index d5ee91c7..3b72e826 100644 --- a/docs/pt/guide/i18n.md +++ b/docs/pt/guide/i18n.md @@ -110,4 +110,4 @@ watchEffect(() => { ## Suporte a RTL (Experimental) {#rtl-support-experimental} -Para suporte a RTL (Right to Left), especifique `dir: 'rtl'` na configuração e use algum plugin RTLCSS PostCSS como , ou . Você precisará configurar seu plugin PostCSS para usar `:where([dir="ltr"])` e `:where([dir="rtl"])` como prefixos para evitar problemas de especificidade CSS. \ No newline at end of file +Para suporte a RTL (Right to Left), especifique `dir: 'rtl'` na configuração e use algum plugin RTLCSS PostCSS como , ou . Você precisará configurar seu plugin PostCSS para usar `:where([dir="ltr"])` e `:where([dir="rtl"])` como prefixos para evitar problemas de especificidade CSS. diff --git a/docs/pt/guide/markdown.md b/docs/pt/guide/markdown.md index 5fba7333..cb2d3e22 100644 --- a/docs/pt/guide/markdown.md +++ b/docs/pt/guide/markdown.md @@ -769,7 +769,7 @@ Por exemplo, você pode incluir um arquivo markdown relativo usando isto: ```md # Documentação -## Conceitos Básicos +## Conceitos Básicos ``` @@ -926,4 +926,4 @@ export default defineConfig({ }) ``` -Consulte a lista completa de propriedades configuráveis em [Referência de Configuração: Configuração da Aplicação](../reference/site-config#markdown). \ No newline at end of file +Consulte a lista completa de propriedades configuráveis em [Referência de Configuração: Configuração da Aplicação](../reference/site-config#markdown). diff --git a/docs/pt/guide/ssr-compat.md b/docs/pt/guide/ssr-compat.md index deec9a7b..e4ed7847 100644 --- a/docs/pt/guide/ssr-compat.md +++ b/docs/pt/guide/ssr-compat.md @@ -133,4 +133,4 @@ const ClientComp = defineClientComponent( ``` -O componente alvo só será importado no gatilho `mounted` do componente que o envolve. \ No newline at end of file +O componente alvo só será importado no gatilho `mounted` do componente que o envolve. diff --git a/docs/pt/guide/using-vue.md b/docs/pt/guide/using-vue.md index 6c2002ac..226d90d2 100644 --- a/docs/pt/guide/using-vue.md +++ b/docs/pt/guide/using-vue.md @@ -223,7 +223,7 @@ Então você pode usar o seguinte em Markdown e nos componentes do tema: ## Usando _Teleports_ {#using-teleports} -Vitepress atualmente oferece suporte a SSG para _teleports_ apenas para o corpo. Para outros alvos, você pode envolvê-los dentro do componente embutido `` ou injetar a marcação de _teleport_ na localização correta em sua página final HTML por meio do [gancho `postRender`](../reference/site-config#postrender). +VitePress atualmente oferece suporte a SSG para _teleports_ apenas para o corpo. Para outros alvos, você pode envolvê-los dentro do componente embutido `` ou injetar a marcação de _teleport_ na localização correta em sua página final HTML por meio do [gancho `postRender`](../reference/site-config#postrender). diff --git a/docs/pt/guide/what-is-vitepress.md b/docs/pt/guide/what-is-vitepress.md index 835f5bd3..734cd417 100644 --- a/docs/pt/guide/what-is-vitepress.md +++ b/docs/pt/guide/what-is-vitepress.md @@ -54,4 +54,4 @@ VitePress é o sucessor espiritual de VuePress. VuePress era orginalmente basead A diferença da API entre VitePress e VuePress reside principalmente em temas e personalização. Se você estiver usando VuePress 1 com o tema padrão, a migração para VitePress deve ser relativamente simples. -Também houve esforço investido em VuePress 2, que também suporta Vue 3 e Vite com melhor compatibilidade do que VuePress 1. No entanto, manter dois SSGs em paralelo não é sustentável, então a equipe Vue decidiu focar em VitePress como o principal SSG recomendado a longo prazo. \ No newline at end of file +Também houve esforço investido em VuePress 2, que também suporta Vue 3 e Vite com melhor compatibilidade do que VuePress 1. No entanto, manter dois SSGs em paralelo não é sustentável, então a equipe Vue decidiu focar em VitePress como o principal SSG recomendado a longo prazo. diff --git a/docs/pt/reference/default-theme-badge.md b/docs/pt/reference/default-theme-badge.md index a96955a0..2fe79aa3 100644 --- a/docs/pt/reference/default-theme-badge.md +++ b/docs/pt/reference/default-theme-badge.md @@ -32,7 +32,7 @@ O código acima é apresentado como: ## Personalize o Tipo de Cor {#customize-type-color} -Você pode personalizar o estilo dos emblemas sobrepondo variáveis ​​CSS. Os seguintes são os valores padrão: +Você pode personalizar o estilo dos emblemas sobrepondo variáveis CSS. Os seguintes são os valores padrão: ```css :root { diff --git a/docs/pt/reference/default-theme-footer.md b/docs/pt/reference/default-theme-footer.md index 98b02b2c..138531e7 100644 --- a/docs/pt/reference/default-theme-footer.md +++ b/docs/pt/reference/default-theme-footer.md @@ -50,4 +50,4 @@ Isso pode ser desabilitado por página usando a opção `footer` em frontmatter: --- footer: false --- -``` \ No newline at end of file +``` diff --git a/docs/pt/reference/default-theme-team-page.md b/docs/pt/reference/default-theme-team-page.md index 9021b959..1daa47a5 100644 --- a/docs/pt/reference/default-theme-team-page.md +++ b/docs/pt/reference/default-theme-team-page.md @@ -100,7 +100,7 @@ const members = [