Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: stable cleanUrls #1852

Merged
merged 3 commits into from
Jan 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default defineConfig({
description: 'Vite & Vue powered static site generator.',

lastUpdated: true,
cleanUrls: 'without-subfolders',
cleanUrls: true,

head: [['meta', { name: 'theme-color', content: '#3c8772' }]],

Expand Down
20 changes: 6 additions & 14 deletions docs/config/app-configs.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,29 +266,21 @@ export default {
}
```

## cleanUrls (Experimental)
## cleanUrls

- Type: `'disabled' | 'without-subfolders' | 'with-subfolders'`
- Default: `'disabled'`
- Type: `boolean`
- Default: `false`

Allows removing trailing `.html` from URLs and, optionally, generating clean directory structure.
Allows removing trailing `.html` from URLs.

```ts
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
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
Expand Down
16 changes: 2 additions & 14 deletions docs/guide/routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,26 +88,14 @@ By default, VitePress generates the final static page files by adding `.html` ex
└─ 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
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

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.
Expand Down
14 changes: 13 additions & 1 deletion src/client/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function createRouter(
async function go(href: string = inBrowser ? location.href : '/') {
await router.onBeforeRouteChange?.(href)
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.
// if cleanUrls is enabled, the server should handle this
if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) {
Expand Down Expand Up @@ -89,6 +89,18 @@ export function createRouter(

if (inBrowser) {
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) {
let target: HTMLElement | null = null
try {
Expand Down
2 changes: 1 addition & 1 deletion src/client/theme-default/components/VPAlgoliaSearchBox.vue
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ function getRelativePath(absoluteUrl: string) {
return (
pathname.replace(
/\.html$/,
site.value.cleanUrls === 'disabled' ? '.html' : ''
site.value.cleanUrls ? '' : '.html'
) + hash
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/client/theme-default/composables/langs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function useLangs({
value.link || (key === 'root' ? '/' : `/${key}/`),
theme.value.i18nRouting !== false && correspondingLink,
page.value.relativePath.slice(currentLang.value.link.length - 1),
site.value.cleanUrls === 'disabled'
!site.value.cleanUrls
)
}
)
Expand Down
2 changes: 1 addition & 1 deletion src/client/theme-default/support/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function normalizeLink(url: string): string {
/(?:(^\.+)\/)?.*$/,
`$1${pathname.replace(
/(\.md)?$/,
site.value.cleanUrls === 'disabled' ? '.html' : ''
site.value.cleanUrls ? '' : '.html'
)}${search}${hash}`
)

Expand Down
9 changes: 1 addition & 8 deletions src/node/build/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,14 +173,7 @@ export async function renderPage(
${inlinedScript}
</body>
</html>`.trim()
const createSubDirectory =
config.cleanUrls === 'with-subfolders' &&
!/(^|\/)(index|404).md$/.test(page)

const htmlFileName = path.join(
config.outDir,
page.replace(/\.md$/, createSubDirectory ? '/index.html' : '.html')
)
const htmlFileName = path.join(config.outDir, page.replace(/\.md$/, '.html'))

await fs.ensureDir(path.dirname(htmlFileName))
const transformedHtml = await config.transformHtml?.(html, htmlFileName, {
Expand Down
17 changes: 5 additions & 12 deletions src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import type { MarkdownOptions } from './markdown/markdown'
import {
APPEARANCE_KEY,
type Awaitable,
type CleanUrlsMode,
type DefaultTheme,
type HeadConfig,
type LocaleConfig,
Expand Down Expand Up @@ -77,17 +76,11 @@ export interface UserConfig<ThemeConfig = any>
ignoreDeadLinks?: boolean | 'localhostLinks'

/**
* @experimental
* Remove '.html' from URLs and generate clean directory structure.
*
* Available Modes:
* - `disabled`: generates `/foo.html` for every `/foo.md` and shows `/foo.html` in browser
* - `without-subfolders`: generates `/foo.html` for every `/foo.md` but shows `/foo` in browser
* - `with-subfolders`: generates `/foo/index.html` for every `/foo.md` and shows `/foo` in browser
* Don't force `.html` on URLs.
*
* @default 'disabled'
* @default false
*/
cleanUrls?: CleanUrlsMode
cleanUrls?: boolean

/**
* Use web fonts instead of emitting font files to dist.
Expand Down Expand Up @@ -279,7 +272,7 @@ export async function resolveConfig(
shouldPreload: userConfig.shouldPreload,
mpa: !!userConfig.mpa,
ignoreDeadLinks: userConfig.ignoreDeadLinks,
cleanUrls: userConfig.cleanUrls || 'disabled',
cleanUrls: !!userConfig.cleanUrls,
useWebFonts:
userConfig.useWebFonts ??
typeof process.versions.webcontainer === 'string',
Expand Down Expand Up @@ -394,7 +387,7 @@ export async function resolveSiteData(
themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {},
scrollOffset: userConfig.scrollOffset || 90,
cleanUrls: userConfig.cleanUrls || 'disabled'
cleanUrls: !!userConfig.cleanUrls
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/node/markdown/env.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
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
// is unable to merge augmented module declarations
Expand Down Expand Up @@ -34,6 +34,6 @@ export interface MarkdownEnv {
title?: string
path: string
relativePath: string
cleanUrls: CleanUrlsMode
cleanUrls: boolean
links?: string[]
}
7 changes: 2 additions & 5 deletions src/node/markdown/plugins/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,11 @@ export const linkPlugin = (
let cleanUrl = url.replace(/[?#].*$/, '')
// transform foo.md -> foo[.html]
if (cleanUrl.endsWith('.md')) {
cleanUrl = cleanUrl.replace(
/\.md$/,
env.cleanUrls === 'disabled' ? '.html' : ''
)
cleanUrl = cleanUrl.replace(/\.md$/, env.cleanUrls ? '' : '.html')
}
// transform ./foo -> ./foo[.html]
if (
env.cleanUrls === 'disabled' &&
!env.cleanUrls &&
!cleanUrl.endsWith('.html') &&
!cleanUrl.endsWith('/')
) {
Expand Down
9 changes: 2 additions & 7 deletions src/node/markdownToVue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@ import c from 'picocolors'
import LRUCache from 'lru-cache'
import { resolveTitleFromToken } from '@mdit-vue/shared'
import type { SiteConfig } from './config'
import {
type PageData,
type HeadConfig,
EXTERNAL_URL_RE,
type CleanUrlsMode
} from './shared'
import { type PageData, type HeadConfig, EXTERNAL_URL_RE } from './shared'
import { slash } from './utils/slash'
import { getGitTimestamp } from './utils/getGitTimestamp'
import {
Expand Down Expand Up @@ -43,7 +38,7 @@ export async function createMarkdownToVueRenderFn(
isBuild = false,
base = '/',
includeLastUpdatedData = false,
cleanUrls: CleanUrlsMode = 'disabled',
cleanUrls = false,
siteConfig: SiteConfig | null = null
) {
const md = await createMarkdownRenderer(srcDir, options, base)
Expand Down
1 change: 0 additions & 1 deletion src/shared/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { HeadConfig, PageData, SiteData } from '../../types/shared.js'

export type {
Awaitable,
CleanUrlsMode,
DefaultTheme,
HeadConfig,
Header,
Expand Down
7 changes: 1 addition & 6 deletions types/shared.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,9 @@ export interface Header {
children: Header[]
}

export type CleanUrlsMode =
| 'disabled'
| 'without-subfolders'
| 'with-subfolders'

export interface SiteData<ThemeConfig = any> {
base: string
cleanUrls?: CleanUrlsMode
cleanUrls?: boolean
lang: string
dir: string
title: string
Expand Down