Jerry's Blog

Back

自定义主题

自己动手定制主题

你需要了解#

本主题被设计为“NPM 包”,原因如下:

  1. 包中编写的代码可能会频繁更改。如果用户随意修改,会显著增加后续更新和合并的成本(各种代码冲突)
  2. 可以轻松回滚和切换不同版本,以保持用户稳定性
  3. 降低系统耦合度,提高复用能力
  4. NPM 包模式可以作为“Astro 插件”,在构建阶段附加额外的操作以增强用户体验
  5. 支持一些内置命令,如 new、check、info 等
  6. 可作为其他 Astro 项目的组件库(是的,本项目可以拆分为 UI 组件库):包详情

在自定义之前,你应该先检查 site.config.ts,确保没有满足你需求的选项。

Swizzling#

本主题选择了一种优雅的方法叫做“Swizzling”,灵感来自 Docusaurus 的设计。

  1. 使用 IDE 快速查看某个组件对应的源代码(在 VSCode 中,按住 Ctrl 点击组件)。
  2. 复制到 src/components/<你喜欢的目录>
  3. 修改后,将相应的引用改为你自己的文件路径。

我们以自定义 Footer 组件为例:

  1. 在项目代码中搜索 Footer

    src/layout/BaseLayout.astro
    ---
    import { Footer, Header, ThemeProvider } from 'astro-pure/components/basic'
    import type { SiteMeta } from 'astro-pure/types'
    // ...
    ---
    astro
  2. 在主题源代码中找到它:

    node_modules/astro-theme-pure/components/basic/index.ts
    export { default as Footer } from './Footer.astro'
    export { default as Header } from './Header.astro'
    export { default as ThemeProvider } from './ThemeProvider.astro'
    ts

    然后你可以在 node_modules/astro-theme-pure/components/basic/Footer.astro 找到 Footer 组件的源代码。

  3. Footer.astro 文件复制到你的项目中:

    cp node_modules/astro-theme-pure/components/basic/Footer.astro src/components/custom/Footer.astro
    bash
  4. 解决子依赖问题:

    src/components/custom/Footer.astro
    ---
    import config from 'virtual:config'
    
    import { Icon } from '../user'
    import { Icon } from 'astro-pure/user'
    // ...
    ---
    astro
  5. BaseLayout.astro 中更改引用:

    src/layout/BaseLayout.astro
     ---
     import { Footer, Header, ThemeProvider } from 'astro-pure/components/basic' // [!code --]
     import { Header, ThemeProvider } from 'astro-pure/components/basic' // [!code ++]
     import { Footer } from '@/components/custom/Footer.astro' // [!code ++]
     // ...
     ---
    astro

这样你就完成了组件的“本地化”。

包模式#

如果你想做一些重大更改或只是进行测试,这种方法可能更符合“所见即所得”。

  1. 确保你有原始主题代码(./packages/pure)。如果已经删除,请从 Releases 下载。
  2. 使用你的包管理器将其链接到你的项目(例如:BunNPMPNPM)。
  3. 然后像修改自己代码的一部分一样修改主题代码!
plaintext