Ownio Blogs 使用指南

欢迎使用 Ownio Blogs!这是一款基于 Astro 构建的现代化个人博客系统,具有优雅的治愈系设计风格、流畅的动画效果和强大的主题定制功能。本指南将详细介绍如何使用和配置你的博客。

目录


项目概述

Ownio Blogs 是一个功能完整的个人博客系统,具有以下特点:

  • 技术栈:Astro 5 + React + Tailwind CSS 4
  • 设计风格:治愈系极简美学,毛玻璃效果,流畅动画
  • 主题系统:9种预设主题色 + 深色模式支持
  • 内容格式:支持 Markdown 和 MDX
  • 响应式设计:完美适配桌面端和移动端
  • 性能优化:图片懒加载、页面过渡动画、SEO 优化

快速开始

安装依赖

npm install
# 或
pnpm install

启动开发服务器

npm run dev

开发服务器将在 http://localhost:4321 启动。

构建生产版本

npm run build

预览生产构建

npm run preview

基础配置

修改站点名称和描述

编辑 src/consts.ts 文件:

export const SITE_TITLE = 'Ownio Blogs';  // 修改为你的博客名称
export const SITE_DESCRIPTION = 'Welcome to my website!';  // 修改为你的博客描述

配置站点 URL

编辑 astro.config.mjs 文件:

export default defineConfig({
  site: 'https://example.com',  // 修改为你的域名
  // ...
});

修改网站标题和元数据

网站标题会自动使用 SITE_TITLE,每个页面可以单独设置标题。例如在 src/pages/index.astro 中:

<BaseHead title={SITE_TITLE} description={SITE_DESCRIPTION} />

主题色系统

Ownio Blogs 内置了 9 种精心设计的主题色,每种主题色都有浅色和深色两个版本。

预设主题色

主题色名称特点主色调
海洋清新自然,适合技术博客#6B8E8D
森林温暖舒适,适合生活博客#7D9B76
日落温暖活力,适合创意博客#D4A76A
薰衣草优雅浪漫,适合文艺博客#A69BB8
玫瑰温柔浪漫,适合情感博客#C8A8A8
黑色极简现代,适合专业博客#8A9BA8
薄荷清新凉爽,适合夏日博客#8CB9BD
沙滩温暖舒适,适合旅行博客#C1A57B
鼠尾草自然宁静,适合环保博客#9CAF88

切换主题色

用户可以通过页面右上角的主题色选择器切换主题色,选择会自动保存到本地存储。

自定义主题色

如果你想添加或修改主题色,编辑 src/stores/theme.ts 文件。

修改现有主题色

找到对应的主题色配置,例如修改”海洋”主题:

ocean: {
  name: '海洋',
  primary: '#6B8E8D',        // 主色调
  primaryLight: '#9DC4C2',   // 浅色变体
  primaryDark: '#4A6A69',    // 深色变体
  accent: '#E8D9CD',         // 强调色
  background: '#F7F4F0',     // 背景色
  surface: '#FFFFFF'          // 表面色
}

添加新主题色

THEME_COLORS 对象中添加新主题:

custom: {
  name: '自定义',
  primary: '#FF6B6B',
  primaryLight: '#FF8E8E',
  primaryDark: '#E85555',
  accent: '#FFE8E8',
  background: '#FFF8F8',
  surface: '#FFFFFF'
}

同时在 DARK_THEME_COLORS 中添加对应的深色版本:

custom: {
  name: '自定义',
  primary: '#FF8E8E',
  primaryLight: '#FFA8A8',
  primaryDark: '#FF7878',
  accent: '#5A3A3A',
  background: '#242020',
  surface: '#343030'
}

深色模式

Ownio Blogs 支持三种深色模式:

  • 浅色模式:始终使用浅色主题
  • 深色模式:始终使用深色主题
  • 自动模式:根据系统设置自动切换

切换深色模式

用户可以通过页面右上角的深色模式切换按钮来切换模式,选择会自动保存。

默认深色模式设置

编辑 src/stores/theme.ts 文件,修改初始主题:

let currentTheme = {
  themeColor: 'ocean',    // 默认主题色
  darkMode: 'light',      // 默认深色模式:'light' | 'dark' | 'auto'
  isDark: false
};

写文章

文章存放位置

所有文章存放在 src/content/blog/ 目录下,支持 .md(Markdown)和 .mdx(MDX)格式。

文章 Frontmatter 格式

每篇文章必须包含 Frontmatter(元数据),格式如下:

---
title: '文章标题'
description: '文章描述,用于 SEO 和列表展示'
pubDate: '2024-01-15'
updatedDate: '2024-01-20'  // 可选:更新日期
heroImage: '../../assets/blog-placeholder-1.jpg'  // 可选:封面图
tags: ['标签1', '标签2', '标签3']  // 可选:文章标签
---

这里是文章内容...

Frontmatter 字段说明

字段类型必填说明
titlestring文章标题
descriptionstring文章描述,用于 SEO 和列表展示
pubDateDate发布日期,格式:‘YYYY-MM-DD’
updatedDateDate更新日期,格式:‘YYYY-MM-DD’
heroImageImage封面图片路径
tagsstring[]文章标签数组

创建新文章

  1. src/content/blog/ 目录下创建新文件,例如 my-new-post.md
  2. 添加 Frontmatter 元数据
  3. 编写文章内容

文章内容格式

Markdown 示例

---
title: '如何使用 Markdown'
description: 'Markdown 语法指南'
pubDate: '2024-01-15'
tags: ['markdown', '写作']
---

# 一级标题

## 二级标题

### 三级标题

这是一段普通文本,**加粗文本***斜体文本*`行内代码`

## 列表

- 无序列表项 1
- 无序列表项 2
- 无序列表项 3

1. 有序列表项 1
2. 有序列表项 2
3. 有序列表项 3

## 链接和图片

[链接文本](https://example.com)

![图片描述](../../assets/blog-placeholder-1.jpg)

## 代码块

```javascript
function hello() {
  console.log('Hello, World!');
}

引用

这是一段引用文本

分隔线


表格

列1列2列3
数据1数据2数据3
数据4数据5数据6

#### MDX 示例

MDX 允许在 Markdown 中使用 React 组件:

```mdx
---
title: '使用 MDX'
description: 'MDX 功能介绍'
pubDate: '2024-01-15'
---

import { Counter } from '../components/Counter';

# MDX 示例

这是一个 MDX 文章,可以在其中使用 React 组件:

<Counter start={0} />

## 常规 Markdown 功能

MDX 完全支持所有 Markdown 语法。

文章排序

文章会按照 pubDate 从新到旧自动排序,最新的文章会显示在最前面。


图片管理

图片存放位置

  • 博客图片src/assets/ 目录
  • 公共资源public/ 目录

图片使用方式

在 Frontmatter 中使用

---
heroImage: '../../assets/blog-placeholder-1.jpg'
---

在文章内容中使用

![图片描述](../../assets/blog-placeholder-1.jpg)

在组件中使用

<ImageWithLoader 
  src={post.data.heroImage} 
  alt="" 
  class="card-image" 
  width={720} 
  height={360} 
/>

图片优化

Ownio Blogs 使用 ImageWithLoader 组件实现图片懒加载和加载动画:

<ImageWithLoader 
  src={imagePath} 
  alt="图片描述" 
  width={720} 
  height={360} 
  objectFit="cover"
/>

支持的图片格式

  • JPG/JPEG
  • PNG
  • WebP(推荐,体积更小)
  • SVG
  • GIF

页面定制

首页定制

首页文件:src/pages/index.astro

修改个人信息

<div class="profile-card-large glass">
  <div class="profile-image-wrapper-large">
    <ImageWithLoader 
      src={AboutImage}  <!-- 修改头像图片 -->
      alt="Profile" 
      class="profile-image-large" 
      width={120} 
      height={120} 
      objectFit="cover" 
    />
  </div>
  <h3 class="profile-name">~IFREAD...</h3>  <!-- 修改名字 -->
  <p class="profile-bio">
    全栈开发者和技术爱好者。分享我在 Web 开发、Astro 等领域的旅程和心得。
  </p>
  <a href="/about" class="btn btn-primary profile-btn">
    了解更多
  </a>
</div>

修改首页文章列表

首页自动显示所有文章,按时间排序。文章卡片样式可以在 <style> 标签中自定义。

关于页定制

关于页文件:src/pages/about.astro

修改个人信息

<h2 class="profile-name-large">~IFREAD...</h2>  <!-- 修改名字 -->
<p class="profile-bio-large">
  全栈开发者 | 技术爱好者  <!-- 修改简介 -->
</p>

修改技能列表

const skills = ['JavaScript', 'TypeScript', 'React', 'Astro', 'Node.js', 'Tailwind CSS', 'Git'];

修改学习经历时间线

const timeline = [
    { year: '2021年', content: '注册洛谷账号,开始系统学习 C++' },
    { year: '2022年', content: '深入数据结构与算法' },
    { year: '2023年', content: '自学嵌入式开发' },
    { year: '2024年', content: '转向 Web 开发' },
    { year: '现在', content: '持续学习,探索更多技术领域', current: true }
];

修改技能分类

const skillCategories = [
    {
        name: '编程语言',
        skills: [
            { name: 'C++', level: 85 },
            { name: 'JavaScript/TypeScript', level: 75 },
            // ...
        ]
    },
    // ...
];

修改联系方式

<div class="contact-item">
  <svg>...</svg>
  <a href="mailto:7@owni.top" class="contact-link">7@owni.top</a>
</div>

归档页定制

归档页文件:src/pages/archive.astro

归档页自动按年份组织所有文章,无需手动配置。样式可以在 <style> 标签中自定义。

导航栏定制

导航栏组件:src/components/Header.astro

修改导航链接

<div class="nav-links">
  <HeaderLink href="/?skip=1">首页</HeaderLink>
  <HeaderLink href="/archive">归档</HeaderLink>
  <HeaderLink href="/about">关于</HeaderLink>
</div>

添加新导航链接

<HeaderLink href="/new-page">新页面</HeaderLink>

页脚定制

页脚组件:src/components/Footer.astro

编辑该文件可以修改页脚内容和样式。


字体系统

当前字体

Ownio Blogs 默认使用 Atkinson 字体,字体文件存放在 public/fonts/ 目录:

  • atkinson-regular.woff - 常规字重
  • atkinson-bold.woff - 粗体字重

替换字体

1. 准备字体文件

将你的字体文件放到 public/fonts/ 目录。

2. 修改字体预加载

编辑 src/components/BaseHead.astro

<link rel="preload" href="/fonts/your-font-regular.woff" as="font" type="font/woff" crossorigin />
<link rel="preload" href="/fonts/your-font-bold.woff" as="font" type="font/woff" crossorigin />

3. 修改全局样式

编辑 src/styles/global.css

@theme {
  --font-family-sans: 'Your Font Name', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  // ...
}

4. 添加字体声明

src/styles/global.css@layer base 中添加:

@font-face {
  font-family: 'Your Font Name';
  src: url('/fonts/your-font-regular.woff') format('woff');
  font-weight: 400;
  font-display: swap;
}

@font-face {
  font-family: 'Your Font Name';
  src: url('/fonts/your-font-bold.woff') format('woff');
  font-weight: 700;
  font-display: swap;
}

使用 Google Fonts

如果你想使用 Google Fonts,可以:

  1. src/components/BaseHead.astro 中添加 Google Fonts 链接:
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  1. src/styles/global.css 中修改字体:
@theme {
  --font-family-sans: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  // ...
}

部署命令

开发环境

npm run dev

启动开发服务器,支持热重载。

生产构建

npm run build

构建生产版本,输出到 dist/ 目录。

预览生产构建

npm run preview

在本地预览生产构建结果。

清理构建缓存

如果遇到构建问题,可以清理缓存:

# 删除 node_modules 和 dist
rm -rf node_modules dist

# 重新安装依赖
npm install

# 重新构建
npm run build

搜索功能

Ownio Blogs 内置了强大的搜索功能,支持实时搜索文章标题、描述和标签。

搜索组件特点

  • 实时搜索:输入关键词即时显示搜索结果
  • 多字段搜索:支持搜索文章标题、描述和标签
  • 关键词高亮:搜索结果中匹配的关键词会高亮显示
  • 快捷键支持:支持 Ctrl/Cmd + K 快捷键打开搜索框
  • 响应式设计:完美适配桌面端和移动端

使用搜索

打开搜索框

点击导航栏右侧的搜索图标,或使用快捷键 Ctrl/Cmd + K 打开搜索框。

搜索内容

在搜索框中输入关键词,搜索会自动匹配:

  • 文章标题
  • 文章描述
  • 文章标签

搜索结果

搜索结果会显示:

  • 文章标题(关键词高亮)
  • 文章描述(关键词高亮)
  • 发布日期
  • 文章标签

点击搜索结果即可跳转到对应文章。

自定义搜索

修改搜索组件

搜索组件位于 src/components/Search.astro,你可以根据需要修改:

<Search posts={posts} />

修改搜索范围

编辑 src/components/Search.astro 中的 performSearch 函数:

function performSearch(query) {
  const results = posts.filter((post) => {
    const title = post.data.title.toLowerCase();
    const description = post.data.description.toLowerCase();
    const tags = (post.data.tags || []).join(' ').toLowerCase();
    // 添加更多搜索字段
    const content = post.body.toLowerCase();
    
    return title.includes(query) || 
           description.includes(query) || 
           tags.includes(query) ||
           content.includes(query);
  });
  // ...
}

修改搜索样式

src/components/Search.astro<style> 标签中修改搜索框样式:

.search-input-container {
  width: 320px;  /* 修改搜索框宽度 */
  background: rgba(255, 255, 255, 0.95);
  /* ... */
}

目录导航

Ownio Blogs 自动为文章生成目录导航,方便用户快速跳转到感兴趣的内容。

目录导航特点

  • 自动生成:根据文章标题自动生成目录
  • 滚动跟随:滚动页面时自动高亮当前章节
  • 平滑滚动:点击目录项平滑滚动到对应位置
  • 响应式设计:在桌面端显示,移动端自动隐藏

目录生成规则

目录会自动包含:

  • 二级标题(##
  • 三级标题(###

一级标题(#)和四级及以下标题不会显示在目录中。

自定义目录

修改目录深度

编辑 src/components/TableOfContents.astro

const filteredHeadings = headings.filter((heading) => 
  heading.depth > 1 && heading.depth < 4  // 修改显示的标题层级
);

修改目录样式

src/components/TableOfContents.astro<style> 标签中修改:

.toc-container {
  padding: 20px;  /* 修改内边距 */
  /* ... */
}

隐藏目录

在文章页面中,你可以选择隐藏目录:

<!-- 不显示目录 -->
<TableOfContents headings={[]} />

滚动进度条

Ownio Blogs 在页面顶部显示阅读进度条,帮助用户了解当前阅读进度。

进度条特点

  • 实时更新:滚动页面时实时更新进度
  • 渐变效果:使用主题色渐变显示进度
  • 发光效果:进度条带有主题色发光效果
  • 性能优化:使用 passive scroll 事件监听,不影响滚动性能

自定义进度条

修改进度条样式

编辑 src/components/ScrollProgress.astro

.progress-bar {
  height: 3px;  /* 修改进度条高度 */
  background: linear-gradient(90deg, var(--color-primary), var(--color-primary-light));
  box-shadow: 0 0 10px var(--color-primary);  /* 修改发光效果 */
}

修改进度条位置

.scroll-progress {
  top: 0;  /* 修改为 bottom: 0 可显示在底部 */
  /* ... */
}

隐藏进度条

在不需要进度条的页面中,可以不引入 ScrollProgress 组件。


页面过渡动画

Ownio Blogs 使用 Astro 的 View Transitions API 实现流畅的页面切换动画。

过渡动画特点

  • 平滑切换:页面切换时使用平滑的过渡效果
  • 保留滚动位置:返回页面时保持之前的滚动位置
  • 浏览器原生:使用浏览器原生的 View Transitions API
  • 性能优化:自动优化动画性能

自定义过渡动画

修改全局过渡效果

编辑 src/styles/global.css

@view-transition {
  navigation: auto;
}

::view-transition-old(root),
::view-transition-new(root) {
  animation-duration: 0.5s;  /* 修改动画时长 */
}

添加自定义过渡动画

src/styles/global.css 中添加:

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

::view-transition-new(root) {
  animation: fade-in 0.5s ease-out;
}

禁用页面过渡

astro.config.mjs 中配置:

export default defineConfig({
  viewTransitions: {
    // 禁用页面过渡
    enabled: false
  }
});

SEO 优化

Ownio Blogs 内置了完善的 SEO 优化功能,帮助你的博客在搜索引擎中获得更好的排名。

基础 SEO 配置

修改站点元数据

编辑 src/consts.ts

export const SITE_TITLE = 'Ownio Blogs';
export const SITE_DESCRIPTION = 'Welcome to my website!';

修改页面标题和描述

src/components/BaseHead.astro 中:

<BaseHead 
  title={SITE_TITLE} 
  description={SITE_DESCRIPTION} 
  image="/og-image.jpg"
/>

Open Graph 标签

Open Graph 标签用于在社交媒体上显示丰富的预览信息。

配置 Open Graph

src/components/BaseHead.astro 中:

<meta property="og:type" content="website" />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={image} />
<meta property="og:url" content={canonicalURL} />
<meta property="og:site_name" content={SITE_TITLE} />

Twitter Cards

Twitter Cards 用于在 Twitter 上显示丰富的预览信息。

配置 Twitter Cards

src/components/BaseHead.astro 中:

<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={image} />

结构化数据

结构化数据帮助搜索引擎更好地理解你的内容。

添加文章结构化数据

src/layouts/BlogPost.astro 中:

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "{post.data.title}",
  "description": "{post.data.description}",
  "datePublished": "{post.data.pubDate}",
  "author": {
    "@type": "Person",
    "name": "Your Name"
  }
}
</script>

自定义 SEO

修改文章页面的 SEO

编辑 src/layouts/BlogPost.astro

<BaseHead 
  title={`${post.data.title} - ${SITE_TITLE}`}
  description={post.data.description}
  image={post.data.heroImage}
/>

添加 Canonical URL

<link rel="canonical" href={`https://yourdomain.com/blog/${post.id}/`} />

部署命令

开发环境

npm run dev

启动开发服务器,支持热重载。

生产构建

npm run build

构建生产版本,输出到 dist/ 目录。

预览生产构建

npm run preview

在本地预览生产构建结果。

清理构建缓存

如果遇到构建问题,可以清理缓存:

# 删除 node_modules 和 dist
rm -rf node_modules dist

# 重新安装依赖
npm install

# 重新构建
npm run build

部署指南

Ownio Blogs 可以轻松部署到多种平台,以下是常见平台的部署指南。

Vercel 部署

Vercel 是一个流行的静态网站托管平台,支持自动部署。

部署步骤

  1. 准备项目

确保你的项目已经推送到 GitHub 仓库。

  1. 导入项目
  • 访问 Vercel
  • 点击 “New Project”
  • 选择你的 GitHub 仓库
  • 点击 “Import”
  1. 配置项目

Vercel 会自动检测 Astro 项目,配置如下:

Framework Preset: Astro
Build Command: npm run build
Output Directory: dist
Install Command: npm install
  1. 部署

点击 “Deploy” 按钮,Vercel 会自动构建和部署你的博客。

  1. 自定义域名

在项目设置中,点击 “Domains”,添加你的自定义域名。

环境变量

如果需要配置环境变量,在项目设置的 “Environment Variables” 中添加。

Netlify 部署

Netlify 是另一个优秀的静态网站托管平台。

部署步骤

  1. 准备项目

确保你的项目已经推送到 GitHub 仓库。

  1. 导入项目
  • 访问 Netlify
  • 点击 “Add new site” > “Import an existing project”
  • 选择你的 GitHub 仓库
  • 点击 “Import site”
  1. 配置构建设置
Build command: npm run build
Publish directory: dist
  1. 部署

点击 “Deploy site”,Netlify 会自动构建和部署。

  1. 自定义域名

在 “Domain settings” 中添加你的自定义域名。

GitHub Pages 部署

GitHub Pages 是 GitHub 提供的免费静态网站托管服务。

部署步骤

  1. 安装 GitHub Actions 工具
npm install -D @astrojs/sitemap
  1. 创建 GitHub Actions 工作流

.github/workflows/deploy.yml 中创建:

name: Deploy to GitHub Pages

on:
  push:
    branches: [ main ]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./dist

      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
  1. 配置 GitHub Pages
  • 进入仓库的 “Settings” > “Pages”
  • Source 选择 “GitHub Actions”
  • 保存设置
  1. 推送代码
git add .
git commit -m "Add GitHub Actions workflow"
git push origin main
  1. 访问博客

部署完成后,你的博客将在 https://yourusername.github.io/your-repo/ 可访问。

Cloudflare Pages 部署

Cloudflare Pages 是一个快速、安全的静态网站托管平台。

部署步骤

  1. 准备项目

确保你的项目已经推送到 GitHub 仓库。

  1. 创建项目
  • 访问 Cloudflare Pages
  • 点击 “Create a project”
  • 选择你的 GitHub 仓库
  • 点击 “Begin setup”
  1. 配置构建设置
Build command: npm run build
Build output directory: dist
  1. 部署

点击 “Save and Deploy”,Cloudflare Pages 会自动构建和部署。

  1. 自定义域名

在 “Custom domains” 中添加你的自定义域名。

自定义域名配置

无论使用哪个平台,你都可以配置自定义域名。

配置 DNS 记录

在你的域名提供商处添加以下 DNS 记录:

类型: CNAME
名称: @ 或 www
值: your-platform-domain.com

配置 SSL

大多数平台会自动为你的域名配置 SSL 证书。


第三方集成

Ownio Blogs 支持多种第三方服务集成,扩展博客功能。

评论系统

Giscus

Giscus 是一个基于 GitHub Discussions 的评论系统。

安装 Giscus
  1. 访问 Giscus
  2. 配置你的仓库和讨论分类
  3. 复制生成的脚本
添加到博客

src/layouts/BlogPost.astro 中添加:

<script src="https://giscus.app/client.js"
  data-repo="your-username/your-repo"
  data-repo-id="your-repo-id"
  data-category="General"
  data-category-id="your-category-id"
  data-mapping="pathname"
  data-strict="0"
  data-reactions-enabled="1"
  data-emit-metadata="0"
  data-input-position="bottom"
  data-theme="preferred_color_scheme"
  data-lang="zh-CN"
  crossorigin="anonymous"
  async>
</script>

Disqus

Disqus 是一个流行的第三方评论系统。

添加 Disqus
  1. 注册 Disqus
  2. 创建新的站点
  3. 复制通用代码

src/layouts/BlogPost.astro 中添加:

<div id="disqus_thread"></div>
<script>
  const disqus_config = function () {
    this.page.url = window.location.href;
    this.page.identifier = "{post.id}";
  };
  
  (function() {
    const d = document, s = d.createElement('script');
    s.src = 'https://your-shortname.disqus.com/embed.js';
    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
  })();
</script>

Google Analytics

Google Analytics 用于跟踪网站访问数据。

添加 Google Analytics

  1. 注册 Google Analytics
  2. 创建新的媒体资源
  3. 复制跟踪 ID

src/components/BaseHead.astro 中添加:

<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script define:vars={{ GA_MEASUREMENT_ID }}>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', GA_MEASUREMENT_ID);
</script>

社交媒体分享

添加分享按钮

创建 src/components/ShareButtons.astro

---
const { url, title } = Astro.props;

const shareLinks = {
  twitter: `https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`,
  facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
  linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,
  weibo: `https://service.weibo.com/share/share.php?title=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`
};
---

<div class="share-buttons">
  <a href={shareLinks.twitter} target="_blank" rel="noopener" class="share-button twitter">
    <svg>...</svg>
    Twitter
  </a>
  <a href={shareLinks.facebook} target="_blank" rel="noopener" class="share-button facebook">
    <svg>...</svg>
    Facebook
  </a>
</div>

<style>
  .share-buttons {
    display: flex;
    gap: 10px;
    margin-top: 20px;
  }
  
  .share-button {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 8px 16px;
    border-radius: 8px;
    text-decoration: none;
    color: white;
    transition: all 0.2s ease;
  }
  
  .share-button:hover {
    transform: translateY(-2px);
  }
  
  .share-button.twitter {
    background: #1DA1F2;
  }
  
  .share-button.facebook {
    background: #4267B2;
  }
</style>

在文章页面中使用:

<ShareButtons 
  url={`https://yourdomain.com/blog/${post.id}/`} 
  title={post.data.title} 
/>

RSS 订阅

Ownio Blogs 内置了 RSS 订阅功能,让用户可以订阅你的博客更新。

RSS 配置

RSS 功能由 @astrojs/rss 集成提供,配置在 astro.config.mjs 中:

import rss from '@astrojs/rss';

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    rss({
      title: 'Ownio Blogs',
      description: 'Welcome to my website!',
      site: 'https://example.com',
      items: await getCollection('blog'),
      customData: `<language>zh-cn</language>`,
    }),
    // ...
  ],
});

自定义 RSS

修改 RSS 内容

编辑 astro.config.mjs 中的 RSS 配置:

rss({
  title: 'Your Blog Title',
  description: 'Your Blog Description',
  site: 'https://example.com',
  items: await getCollection('blog'),
  customData: `<language>zh-cn</language>`,
  stylesheet: '/rss.xsl',  // 添加 RSS 样式表
})

添加 RSS 样式表

创建 public/rss.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <head>
        <title>RSS Feed</title>
        <style>
          body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
          .item { margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid #eee; }
          .title { font-size: 1.2em; font-weight: bold; }
          .date { color: #666; font-size: 0.9em; }
        </style>
      </head>
      <body>
        <h1>RSS Feed</h1>
        <xsl:for-each select="rss/channel/item">
          <div class="item">
            <div class="title">
              <a href="{link}">
                <xsl:value-of select="title"/>
              </a>
            </div>
            <div class="date">
              <xsl:value-of select="pubDate"/>
            </div>
            <div class="description">
              <xsl:value-of select="description" disable-output-escaping="yes"/>
            </div>
          </div>
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

添加 RSS 订阅链接

在导航栏中添加 RSS 订阅链接:

<a href="/rss.xml" class="rss-link">
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M4 11a9 9 0 0 1 9 9"></path>
    <path d="M4 4a16 16 0 0 1 16 16"></path>
    <circle cx="5" cy="19" r="1"></circle>
  </svg>
  RSS
</a>

站点地图

Ownio Blogs 自动生成站点地图(Sitemap),帮助搜索引擎更好地索引你的博客。

Sitemap 配置

Sitemap 功能由 @astrojs/sitemap 集成提供,配置在 astro.config.mjs 中:

import sitemap from '@astrojs/sitemap';

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    sitemap(),
    // ...
  ],
});

自定义 Sitemap

排除页面

astro.config.mjs 中配置排除的页面:

sitemap({
  filter: (page) => !page.pathname.includes('/private'),
})

修改 Sitemap 生成规则

sitemap({
  changefreq: 'weekly',
  priority: 0.7,
  lastmod: new Date(),
})

提交 Sitemap 到搜索引擎

Google Search Console

  1. 访问 Google Search Console
  2. 添加你的站点
  3. 在 “站点地图” 中提交 https://example.com/sitemap-index.xml

Bing Webmaster Tools

  1. 访问 Bing Webmaster Tools
  2. 添加你的站点
  3. 在 “站点地图” 中提交 https://example.com/sitemap-index.xml

性能优化

Ownio Blogs 内置了多种性能优化功能,确保你的博客快速加载。

图片优化

使用 ImageWithLoader 组件

Ownio Blogs 使用 ImageWithLoader 组件实现图片懒加载和加载动画:

<ImageWithLoader 
  src={imagePath} 
  alt="图片描述" 
  width={720} 
  height={360} 
  objectFit="cover"
/>

图片格式优化

  • 使用 WebP 格式(体积更小)
  • 提供多种尺寸的图片
  • 使用响应式图片
<picture>
  <source srcset={imageWebP} type="image/webp" />
  <source srcset={imageJpg} type="image/jpeg" />
  <img src={imageJpg} alt="图片描述" loading="lazy" />
</picture>

代码分割

按需加载组件

Astro 默认会进行代码分割,你也可以手动配置:

export default defineConfig({
  build: {
    inlineStylesheets: 'auto',
  },
});

缓存策略

配置缓存头

public/_headers 中添加:

/assets/*
  Cache-Control: public, max-age=31536000, immutable

/*.js
  Cache-Control: public, max-age=31536000, immutable

/*.css
  Cache-Control: public, max-age=31536000, immutable

/*.html
  Cache-Control: public, max-age=0, must-revalidate

预加载关键资源

预加载字体

src/components/BaseHead.astro 中:

<link rel="preload" href="/fonts/atkinson-regular.woff" as="font" type="font/woff" crossorigin />
<link rel="preload" href="/fonts/atkinson-bold.woff" as="font" type="font/woff" crossorigin />

预加载关键 CSS

<link rel="preload" href="/styles/global.css" as="style" />

压缩资源

启用 Gzip 压缩

在部署平台(如 Vercel、Netlify)中启用 Gzip 压缩。

使用 Brotli 压缩

Brotli 压缩比 Gzip 更高效,在支持的平台中启用。

性能监控

使用 Lighthouse

定期使用 Lighthouse 检查网站性能:

npm install -g lighthouse
lighthouse https://yourdomain.com --view

使用 Web Vitals

在博客中添加 Web Vitals 监控:

<script>
  import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

  getCLS(console.log);
  getFID(console.log);
  getFCP(console.log);
  getLCP(console.log);
  getTTFB(console.log);
</script>

高级配置

自定义 CSS 变量

编辑 src/styles/global.css 可以自定义更多 CSS 变量:

@theme {
  --color-primary: #6B8E8D;
  --color-primary-light: #9DC4C2;
  --color-primary-dark: #4A6A69;
  --color-accent: #E8D9CD;
  --color-background: #F7F4F0;
  --color-surface: #FFFFFF;
  --color-text-base: #3A4746;
  --color-text-muted: #6C7A79;
  --color-border: #E8E4DF;
  --font-family-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  
  --breakpoint-sm: 640px;
  --breakpoint-md: 768px;
  --breakpoint-lg: 1024px;
  --breakpoint-xl: 1280px;
}

修改背景图片

编辑 src/styles/global.css,找到 body::before 样式:

body::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('/images/your-background-image.jpg');  // 修改背景图片
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  filter: blur(12px);
  z-index: -1;
}

添加自定义组件

src/components/ 目录下创建新组件,例如 MyComponent.astro

---
interface Props {
  title: string;
}

const { title } = Astro.props;
---

<div class="my-component">
  <h2>{title}</h2>
</div>

<style>
  .my-component {
    padding: 2rem;
    background: var(--color-surface);
    border-radius: 16px;
  }
</style>

然后在页面中使用:

import MyComponent from '../components/MyComponent.astro';

<MyComponent title="自定义组件" />

常见问题

Q: 如何修改默认主题色?

A: 编辑 src/stores/theme.ts,修改 currentTheme.themeColor 的值。

Q: 如何添加新的博客页面?

A: 在 src/pages/ 目录下创建新的 .astro 文件,例如 src/pages/projects.astro

Q: 如何修改文章的 URL?

A: 文章的 URL 由文件名决定,例如 my-post.md 的 URL 是 /blog/my-post/。修改文件名即可改变 URL。

Q: 如何启用评论功能?

A: Ownio Blogs 默认不包含评论功能,你可以集成第三方评论系统如 Giscus、Disqus 或 Utterances。

Q: 如何添加 Google Analytics?

A: 在 src/components/BaseHead.astro 中添加 Google Analytics 代码:

<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script define:vars={{ GA_MEASUREMENT_ID }}>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', GA_MEASUREMENT_ID);
</script>

Q: 如何自定义文章的 SEO?

A: 在 src/layouts/BlogPost.astro 中可以自定义文章页面的 SEO 元数据。


技术支持

如有问题或建议,欢迎通过以下方式联系:

  • 邮箱:7@owni.top
  • GitHub Issues:[项目仓库地址]

许可证

Ownio Blogs 采用 MIT 许可证,你可以自由使用、修改和分发。


祝你使用 Ownio Blogs 愉快!