Skip to content

Commit

Permalink
feat: emit 404.html on build (#729) (#740)
Browse files Browse the repository at this point in the history
close #729 

Co-authored-by: Kia Ishii <[email protected]>
  • Loading branch information
brc-dd and kiaking authored Jun 14, 2022
1 parent 263607b commit 23276ba
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 33 deletions.
13 changes: 2 additions & 11 deletions src/client/app/router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue'
import { PageData } from '../shared'
import { PageData, notFoundPageData } from '../shared'
import { inBrowser, withBase } from './utils'
import { siteDataRef } from './data'

Expand All @@ -21,15 +21,6 @@ export const RouterSymbol: InjectionKey<Router> = Symbol()
// matter and is only passed to support same-host hrefs.
const fakeHost = `http://a.com`

const notFoundPageData: PageData = {
relativePath: '',
title: '404',
description: 'Not Found',
headers: [],
frontmatter: {},
lastUpdated: 0
}

const getDefaultRoute = (): Route => ({
path: '/',
component: null,
Expand Down Expand Up @@ -109,7 +100,7 @@ export function createRouter(
}
}
} catch (err: any) {
if (!err.message.match(/fetch/)) {
if (!err.message.match(/fetch/) && !href.match(/^[\\/]404\.html$/)) {
console.error(err)
}

Expand Down
4 changes: 3 additions & 1 deletion src/node/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ export async function build(
// as JS object literal.
const hashMapString = JSON.stringify(JSON.stringify(pageToHashMap))

for (const page of siteConfig.pages) {
const pages = ['404.md', ...siteConfig.pages]

for (const page of pages) {
await renderPage(
siteConfig,
page,
Expand Down
55 changes: 34 additions & 21 deletions src/node/build/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { pathToFileURL } from 'url'
import escape from 'escape-html'
import { normalizePath, transformWithEsbuild } from 'vite'
import { RollupOutput, OutputChunk, OutputAsset } from 'rollup'
import { HeadConfig, createTitle } from '../shared'
import { HeadConfig, PageData, createTitle, notFoundPageData } from '../shared'
import { slash } from '../utils/slash'
import { SiteConfig, resolveSiteDataByRoute } from '../config'

Expand Down Expand Up @@ -52,28 +52,41 @@ export async function renderPage(
const pageHash = pageToHashMap[pageName.toLowerCase()]
const pageClientJsFileName = `assets/${pageName}.${pageHash}.lean.js`

// resolve page data so we can render head tags
const { __pageData } = await import(
pathToFileURL(path.join(config.tempDir, pageServerJsFileName)).toString()
)
const pageData = JSON.parse(__pageData)
let pageData: PageData
let hasCustom404 = true

try {
// resolve page data so we can render head tags
const { __pageData } = await import(
pathToFileURL(path.join(config.tempDir, pageServerJsFileName)).toString()
)
pageData = JSON.parse(__pageData)
} catch (e) {
if (page === '404.md') {
hasCustom404 = false
pageData = notFoundPageData
} else {
throw e
}
}

let preloadLinks = config.mpa
? appChunk
? [appChunk.fileName]
let preloadLinks =
config.mpa || (!hasCustom404 && page === '404.md')
? appChunk
? [appChunk.fileName]
: []
: result && appChunk
? [
...new Set([
// resolve imports for index.js + page.md.js and inject script tags
// for them as well so we fetch everything as early as possible
// without having to wait for entry chunks to parse
...resolvePageImports(config, page, result, appChunk),
pageClientJsFileName,
appChunk.fileName
])
]
: []
: result && appChunk
? [
...new Set([
// resolve imports for index.js + page.md.js and inject script tags for
// them as well so we fetch everything as early as possible without having
// to wait for entry chunks to parse
...resolvePageImports(config, page, result, appChunk),
pageClientJsFileName,
appChunk.fileName
])
]
: []

let prefetchLinks: string[] = []

Expand Down
9 changes: 9 additions & 0 deletions src/shared/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ export const APPEARANCE_KEY = 'vitepress-theme-appearance'
// @ts-ignore
export const inBrowser = typeof window !== 'undefined'

export const notFoundPageData: PageData = {
relativePath: '',
title: '404',
description: 'Not Found',
headers: [],
frontmatter: {},
lastUpdated: 0
}

function findMatchRoot(route: string, roots: string[]): string | undefined {
// first match to the routes with the most deep level.
roots.sort((a, b) => {
Expand Down

0 comments on commit 23276ba

Please sign in to comment.