feat: stable `cleanUrls` (#1852)

pull/1853/head
Divyansh Singh 2 years ago committed by GitHub
parent 00abac6116
commit 5ae4fbde38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,7 +10,7 @@ export default defineConfig({
description: 'Vite & Vue powered static site generator.', description: 'Vite & Vue powered static site generator.',
lastUpdated: true, lastUpdated: true,
cleanUrls: 'without-subfolders', cleanUrls: true,
head: [['meta', { name: 'theme-color', content: '#3c8772' }]], head: [['meta', { name: 'theme-color', content: '#3c8772' }]],

@ -266,29 +266,21 @@ export default {
} }
``` ```
## cleanUrls (Experimental) ## cleanUrls
- Type: `'disabled' | 'without-subfolders' | 'with-subfolders'` - Type: `boolean`
- Default: `'disabled'` - Default: `false`
Allows removing trailing `.html` from URLs and, optionally, generating clean directory structure. Allows removing trailing `.html` from URLs.
```ts ```ts
export default { export default {
cleanUrls: 'with-subfolders' cleanUrls: true
} }
``` ```
This option has several modes you can choose. Here is the list of all modes available.
| Mode | Page | Generated Page | URL |
| :--------------------- | :-------- | :---------------- | :---------- |
| `'disabled'` | `/foo.md` | `/foo.html` | `/foo.html` |
| `'without-subfolders'` | `/foo.md` | `/foo.html` | `/foo` |
| `'with-subfolders'` | `/foo.md` | `/foo/index.html` | `/foo` |
::: warning ::: warning
Enabling this may require additional configuration on your hosting platform. For it to work, your server must serve the generated page on requesting the URL **without a redirect**. Enabling this may require additional configuration on your hosting platform. For it to work, your server must serve `/foo.html` on requesting `/foo` **without a redirect**.
::: :::
## rewrites ## rewrites

@ -88,26 +88,14 @@ By default, VitePress generates the final static page files by adding `.html` ex
└─ index.md └─ index.md
``` ```
However, you may also generate a clean URL by setting up [`cleanUrls`](/config/app-configs#cleanurls-experimental) option. However, you may also generate a clean URL by setting up [`cleanUrls`](/config/app-configs#cleanurls) option.
```ts ```ts
export default { export default {
cleanUrls: 'with-subfolders' cleanUrls: true
} }
``` ```
This option has several modes you can choose. Here is the list of all modes available. The default behavior is `disabled` mode.
| Mode | Page | Generated Page | URL |
| :--------------------- | :-------- | :---------------- | :---------- |
| `'disabled'` | `/foo.md` | `/foo.html` | `/foo.html` |
| `'without-subfolders'` | `/foo.md` | `/foo.html` | `/foo` |
| `'with-subfolders'` | `/foo.md` | `/foo/index.html` | `/foo` |
::: warning
Enabling this may require additional configuration on your hosting platform. For it to work, your server must serve the generated page on requesting the URL **without a redirect**.
:::
## Customize the Mappings ## Customize the Mappings
You may customize the mapping between directory structure and URL. It's useful when you have complex document structure. For example, let's say you have several packages and would like to place documentations along with the source files like this. You may customize the mapping between directory structure and URL. It's useful when you have complex document structure. For example, let's say you have several packages and would like to place documentations along with the source files like this.

@ -49,7 +49,7 @@ export function createRouter(
async function go(href: string = inBrowser ? location.href : '/') { async function go(href: string = inBrowser ? location.href : '/') {
await router.onBeforeRouteChange?.(href) await router.onBeforeRouteChange?.(href)
const url = new URL(href, fakeHost) const url = new URL(href, fakeHost)
if (siteDataRef.value.cleanUrls === 'disabled') { if (!siteDataRef.value.cleanUrls) {
// ensure correct deep link so page refresh lands on correct files. // ensure correct deep link so page refresh lands on correct files.
// if cleanUrls is enabled, the server should handle this // if cleanUrls is enabled, the server should handle this
if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) { if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) {
@ -89,6 +89,18 @@ export function createRouter(
if (inBrowser) { if (inBrowser) {
nextTick(() => { nextTick(() => {
let actualPathname =
'/' +
__pageData.relativePath.replace(/(?:(^|\/)index)?\.md$/, '$1')
if (!siteDataRef.value.cleanUrls && !actualPathname.endsWith('/')) {
actualPathname += '.html'
}
if (actualPathname !== targetLoc.pathname) {
targetLoc.pathname = actualPathname
href = actualPathname + targetLoc.search + targetLoc.hash
history.replaceState(null, '', href)
}
if (targetLoc.hash && !scrollPosition) { if (targetLoc.hash && !scrollPosition) {
let target: HTMLElement | null = null let target: HTMLElement | null = null
try { try {

@ -90,7 +90,7 @@ function getRelativePath(absoluteUrl: string) {
return ( return (
pathname.replace( pathname.replace(
/\.html$/, /\.html$/,
site.value.cleanUrls === 'disabled' ? '.html' : '' site.value.cleanUrls ? '' : '.html'
) + hash ) + hash
) )
} }

@ -24,7 +24,7 @@ export function useLangs({
value.link || (key === 'root' ? '/' : `/${key}/`), value.link || (key === 'root' ? '/' : `/${key}/`),
theme.value.i18nRouting !== false && correspondingLink, theme.value.i18nRouting !== false && correspondingLink,
page.value.relativePath.slice(currentLang.value.link.length - 1), page.value.relativePath.slice(currentLang.value.link.length - 1),
site.value.cleanUrls === 'disabled' !site.value.cleanUrls
) )
} }
) )

@ -44,7 +44,7 @@ export function normalizeLink(url: string): string {
/(?:(^\.+)\/)?.*$/, /(?:(^\.+)\/)?.*$/,
`$1${pathname.replace( `$1${pathname.replace(
/(\.md)?$/, /(\.md)?$/,
site.value.cleanUrls === 'disabled' ? '.html' : '' site.value.cleanUrls ? '' : '.html'
)}${search}${hash}` )}${search}${hash}`
) )

@ -173,14 +173,7 @@ export async function renderPage(
${inlinedScript} ${inlinedScript}
</body> </body>
</html>`.trim() </html>`.trim()
const createSubDirectory = const htmlFileName = path.join(config.outDir, page.replace(/\.md$/, '.html'))
config.cleanUrls === 'with-subfolders' &&
!/(^|\/)(index|404).md$/.test(page)
const htmlFileName = path.join(
config.outDir,
page.replace(/\.md$/, createSubDirectory ? '/index.html' : '.html')
)
await fs.ensureDir(path.dirname(htmlFileName)) await fs.ensureDir(path.dirname(htmlFileName))
const transformedHtml = await config.transformHtml?.(html, htmlFileName, { const transformedHtml = await config.transformHtml?.(html, htmlFileName, {

@ -16,7 +16,6 @@ import type { MarkdownOptions } from './markdown/markdown'
import { import {
APPEARANCE_KEY, APPEARANCE_KEY,
type Awaitable, type Awaitable,
type CleanUrlsMode,
type DefaultTheme, type DefaultTheme,
type HeadConfig, type HeadConfig,
type LocaleConfig, type LocaleConfig,
@ -77,17 +76,11 @@ export interface UserConfig<ThemeConfig = any>
ignoreDeadLinks?: boolean | 'localhostLinks' ignoreDeadLinks?: boolean | 'localhostLinks'
/** /**
* @experimental * Don't force `.html` on URLs.
* Remove '.html' from URLs and generate clean directory structure.
*
* Available Modes:
* - `disabled`: generates `/foo.html` for every `/foo.md` and shows `/foo.html` in browser
* - `without-subfolders`: generates `/foo.html` for every `/foo.md` but shows `/foo` in browser
* - `with-subfolders`: generates `/foo/index.html` for every `/foo.md` and shows `/foo` in browser
* *
* @default 'disabled' * @default false
*/ */
cleanUrls?: CleanUrlsMode cleanUrls?: boolean
/** /**
* Use web fonts instead of emitting font files to dist. * Use web fonts instead of emitting font files to dist.
@ -279,7 +272,7 @@ export async function resolveConfig(
shouldPreload: userConfig.shouldPreload, shouldPreload: userConfig.shouldPreload,
mpa: !!userConfig.mpa, mpa: !!userConfig.mpa,
ignoreDeadLinks: userConfig.ignoreDeadLinks, ignoreDeadLinks: userConfig.ignoreDeadLinks,
cleanUrls: userConfig.cleanUrls || 'disabled', cleanUrls: !!userConfig.cleanUrls,
useWebFonts: useWebFonts:
userConfig.useWebFonts ?? userConfig.useWebFonts ??
typeof process.versions.webcontainer === 'string', typeof process.versions.webcontainer === 'string',
@ -394,7 +387,7 @@ export async function resolveSiteData(
themeConfig: userConfig.themeConfig || {}, themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {}, locales: userConfig.locales || {},
scrollOffset: userConfig.scrollOffset || 90, scrollOffset: userConfig.scrollOffset || 90,
cleanUrls: userConfig.cleanUrls || 'disabled' cleanUrls: !!userConfig.cleanUrls
} }
} }

@ -1,5 +1,5 @@
import type { MarkdownSfcBlocks } from '@mdit-vue/plugin-sfc' import type { MarkdownSfcBlocks } from '@mdit-vue/plugin-sfc'
import type { CleanUrlsMode, Header } from '../shared' import type { Header } from '../shared'
// Manually declaring all properties as rollup-plugin-dts // Manually declaring all properties as rollup-plugin-dts
// is unable to merge augmented module declarations // is unable to merge augmented module declarations
@ -34,6 +34,6 @@ export interface MarkdownEnv {
title?: string title?: string
path: string path: string
relativePath: string relativePath: string
cleanUrls: CleanUrlsMode cleanUrls: boolean
links?: string[] links?: string[]
} }

@ -68,14 +68,11 @@ export const linkPlugin = (
let cleanUrl = url.replace(/[?#].*$/, '') let cleanUrl = url.replace(/[?#].*$/, '')
// transform foo.md -> foo[.html] // transform foo.md -> foo[.html]
if (cleanUrl.endsWith('.md')) { if (cleanUrl.endsWith('.md')) {
cleanUrl = cleanUrl.replace( cleanUrl = cleanUrl.replace(/\.md$/, env.cleanUrls ? '' : '.html')
/\.md$/,
env.cleanUrls === 'disabled' ? '.html' : ''
)
} }
// transform ./foo -> ./foo[.html] // transform ./foo -> ./foo[.html]
if ( if (
env.cleanUrls === 'disabled' && !env.cleanUrls &&
!cleanUrl.endsWith('.html') && !cleanUrl.endsWith('.html') &&
!cleanUrl.endsWith('/') !cleanUrl.endsWith('/')
) { ) {

@ -4,12 +4,7 @@ import c from 'picocolors'
import LRUCache from 'lru-cache' import LRUCache from 'lru-cache'
import { resolveTitleFromToken } from '@mdit-vue/shared' import { resolveTitleFromToken } from '@mdit-vue/shared'
import type { SiteConfig } from './config' import type { SiteConfig } from './config'
import { import { type PageData, type HeadConfig, EXTERNAL_URL_RE } from './shared'
type PageData,
type HeadConfig,
EXTERNAL_URL_RE,
type CleanUrlsMode
} from './shared'
import { slash } from './utils/slash' import { slash } from './utils/slash'
import { getGitTimestamp } from './utils/getGitTimestamp' import { getGitTimestamp } from './utils/getGitTimestamp'
import { import {
@ -43,7 +38,7 @@ export async function createMarkdownToVueRenderFn(
isBuild = false, isBuild = false,
base = '/', base = '/',
includeLastUpdatedData = false, includeLastUpdatedData = false,
cleanUrls: CleanUrlsMode = 'disabled', cleanUrls = false,
siteConfig: SiteConfig | null = null siteConfig: SiteConfig | null = null
) { ) {
const md = await createMarkdownRenderer(srcDir, options, base) const md = await createMarkdownRenderer(srcDir, options, base)

@ -2,7 +2,6 @@ import type { HeadConfig, PageData, SiteData } from '../../types/shared.js'
export type { export type {
Awaitable, Awaitable,
CleanUrlsMode,
DefaultTheme, DefaultTheme,
HeadConfig, HeadConfig,
Header, Header,

7
types/shared.d.ts vendored

@ -43,14 +43,9 @@ export interface Header {
children: Header[] children: Header[]
} }
export type CleanUrlsMode =
| 'disabled'
| 'without-subfolders'
| 'with-subfolders'
export interface SiteData<ThemeConfig = any> { export interface SiteData<ThemeConfig = any> {
base: string base: string
cleanUrls?: CleanUrlsMode cleanUrls?: boolean
lang: string lang: string
dir: string dir: string
title: string title: string

Loading…
Cancel
Save