主题

主题全权掌控布局(HTML 模板)、默认 MDX 组件,以及可选的主题页面与静态资源。Methanol 仓库中的默认主题可作为最佳参考范例。

主题开发指南

主题配置结构

export default () => ({
	theme: {
		root: './theme',
		componentsDir: './components',
		pagesDir: './pages',
		publicDir: './public',
		sources: {
			'/theme': './sources'
		},
		template: ({ PageContent, ExtraHead, ctx, page, withBase, HTMLRenderer, components }) => (
			<>
				{HTMLRenderer.rawHTML`<!doctype html>`}
				<html lang="en">
					<head>
						<meta charset="UTF-8" />
						<meta name="viewport" content="width=device-width" />
						<ExtraHead />
						<title>{page.title || ctx.site.name}</title>
						<link rel="icon" href="/favicon.png" />
					</head>
					<body>
						{components.Callout ? <components.Callout>Hi</components.Callout> : null}
						<PageContent />
					</body>
				</html>
			</>
		),
		components: {
			Callout: ({ children }) => <div class="callout">{children}</div>
		}
	}
})

必填

默认值与校验

推荐目录结构

建议结构:

theme/
  index.js          # 主题配置入口
  page.jsx          # 布局模板组件
  components/       # 默认 MDX 组件集合
  pages/            # 主题预设页面
  public/           # 主题静态资源
  sources/          # theme.sources 映射资源目录

主题的 public/ 目录将在 dev/build 阶段合并至项目的 publicDir。若遇同名文件冲突,项目资源优先级高于主题资源。

模板接口规范

theme.template 接收以下参数:

函数需返回一个完整的 JSX 树。

**重要:**务必将 <ExtraHead /> 置于 <head> 标签内,否则页面 <Head>/head 及自动注入资源将无法生效。

当站点部署于子路径(site.base !== '/')时:

主题默认组件

theme.components 定义主题默认 MDX 组件。用户 components/ 目录下的同名组件将覆盖主题组件。

模板亦会接收 components 对象(便于在布局中调用,如导航、搜索组件等)。

主题预设页面机制

主题页面遵循与用户页面一致的路由规则。用户页面始终拥有更高优先级。

主题提供的 /404 页面仅在用户未定义 404 页面时生效。

主题静态资源合并

若主题配置了 publicDir,其内容将在 dev/build 启动时复制至用户 public 目录。即使用户已配置 publicDir,主题资源仍会被复制,同名文件将自动跳过。若用户侧未创建 public 目录,则直接使用主题的 public 目录。

主题资源映射

theme.sources 将虚拟 URL 映射至物理文件。该机制由 Methanol 解析器处理,而非 Vite alias。

export default () => ({
	theme: {
		root: './theme',
		sources: {
			'/theme': './sources'
		}
	}
})

构建钩子(Hooks)

主题亦可提供构建钩子(结构与用户配置 hook 一致):