Skip to content

环境设置

本指南详细介绍如何为 Hugo 网站项目搭建完整的开发环境,包括所需工具、依赖和配置方法。

系统要求

最低要求

  • 操作系统:macOS 10.15+、Ubuntu 20.04+、Windows 10+
  • 内存:8GB RAM(推荐 16GB)
  • 存储空间:10GB 可用空间
  • 网络:稳定的互联网连接用于下载依赖

推荐配置

  • CPU:多核处理器(推荐 4 核及以上)
  • 内存:16GB+ RAM,性能更佳
  • 存储空间:SSD,20GB+ 可用空间
  • 网络:高速网络,提升开发效率

核心依赖

1. Hugo Extended

Hugo Extended 版本用于 SCSS 处理和高级功能。

安装方法:

# macOS(Homebrew)
brew install hugo

# Ubuntu/Debian
sudo apt-get install hugo

# Windows(Chocolatey)
choco install hugo-extended

# 验证安装
hugo version

要求版本:v0.147.8 或更高

必须安装 Hugo Extended

请确保安装的是 Hugo Extended 版本,标准版不支持 SCSS/Sass,本项目必须使用扩展版。

2. Node.js 和 npm

Node.js 用于构建工具、资源处理和开发脚本。

安装方法:

# 推荐使用 Node Version Manager
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 20
nvm use 20

# 验证安装
node --version  # 应为 v20.x.x
npm --version   # 应为 10.x.x

其他安装方式:

# macOS(Homebrew)
brew install node

# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

# Windows
# 官网下载 https://nodejs.org/

3. Python 3.9+

Python 用于 PDF 导出、内容分析和自动化脚本。

安装方法:

# macOS(Homebrew)
brew install [email protected]

# Ubuntu/Debian
sudo apt-get install python3 python3-pip python3-venv

# Windows
# 官网下载 https://python.org/downloads/

# 验证安装
python3 --version  # 应为 3.9+
pip3 --version

4. Git

Git 用于版本管理和协作。

安装方法:

# macOS(Homebrew)
brew install git

# Ubuntu/Debian
sudo apt-get install git

# Windows
# 官网下载 https://git-scm.com/

# 配置 Git
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

可选依赖

1. Pandoc(用于 PDF 导出)

高级 PDF 导出功能需要 Pandoc。

安装方法:

# macOS
brew install pandoc

# Ubuntu/Debian
sudo apt-get install pandoc

# Windows
# 官网下载 https://pandoc.org/installing.html

2. XeLaTeX(用于 PDF 导出)

高质量 PDF 生成及中文字体支持。

安装方法:

# macOS
brew install --cask mactex

# Ubuntu/Debian
sudo apt-get install texlive-xetex texlive-fonts-recommended texlive-fonts-extra

# Windows
# 官网下载 MiKTeX https://miktex.org/

3. Cloudflare Tunnel(开发预览)

用于创建公网开发预览。

安装方法:

# macOS
brew install cloudflared

# Ubuntu/Debian
wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared-linux-amd64.deb

# Windows
# 官网下载 https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/

4. rclone(图片上传)

自动优化图片并上传至 Cloudflare R2。

安装方法:

# macOS
brew install rclone

# Ubuntu/Debian
sudo apt-get install rclone

# Windows
# 官网下载 https://rclone.org/downloads/

项目初始化

1. 克隆仓库

git clone https://github.com/rootsongjc/website.git
cd website

2. 安装 Node.js 依赖

npm install

安装内容包括:

  • 构建工具:PostCSS、Autoprefixer、Terser
  • 内容处理:Gray Matter、Image Size、Glob
  • 开发工具:Puppeteer、Markdownlint
  • 资源处理:Mermaid CLI、Sharp、Pako

3. 安装 Python 依赖

# 推荐创建虚拟环境
python3 -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# 安装依赖
pip install -r requirements.txt

4. 验证安装

运行依赖检查:

make check-deps

预期输出:

Hugo: ✓ hugo v0.147.8+extended
Python3: ✓ Python 3.11.x
Pandoc: ✓ pandoc 3.x.x
XeLaTeX: ✓ 已安装
Cloudflared: ✓ cloudflared 2024.x.x

开发工具配置

1. VS Code 设置

推荐扩展:

{
  "recommendations": [
    "bungcip.better-toml",
    "davidanson.vscode-markdownlint",
    "ms-vscode.vscode-json",
    "bradlc.vscode-tailwindcss",
    "golang.go",
    "ms-python.python",
    "yzhang.markdown-all-in-one",
    "bierner.markdown-mermaid",
    "streetsidesoftware.code-spell-checker"
  ]
}

工作区设置:

{
  "files.associations": {
    "*.toml": "toml",
    "*.md": "markdown"
  },
  "markdown.extension.toc.levels": "2..4",
  "markdownlint.config": {
    "MD013": false,
    "MD033": false
  },
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.markdownlint": true
  }
}

2. Git 配置

设置 Git 钩子:

# 创建 pre-commit 钩子
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
# 提交前运行测试
npm run test:fast
if [ $? -ne 0 ]; then
  echo "测试未通过,终止提交。"
  exit 1
fi
EOF

chmod +x .git/hooks/pre-commit

配置 Git 忽略文件:

项目包含完善的 .gitignore,主要忽略内容:

# 构建输出
public/
resources/
node_modules/

# 开发文件
.DS_Store
*.log
.env

# 缓存目录
.hugo_build.lock
image-caches/

# Python
__pycache__/
*.pyc
venv/

3. 环境变量

本地开发请创建 .env 文件:

# .env(不提交至 git)
HUGO_ENVIRONMENT=development
CLOUDFLARE_R2_ACCESS_KEY=your_access_key
CLOUDFLARE_R2_SECRET_KEY=your_secret_key
GOOGLE_ANALYTICS_ID=UA-XXXXXXXX-X

开发流程

1. 日常开发

启动开发服务器:

# 基础 Hugo 服务器
hugo server

# 文件编辑增强开发
make server

# Cloudflare Tunnel 开发
make dev

开发访问地址:

  • 本地http://localhost:1313
  • 局域网http://[your-ip]:1313
  • Cloudflare Tunnelhttps://dev.jimmysong.io

2. 构建与测试

构建网站:

# 开发构建
hugo

# 生产构建
npm run build

# 清理后构建
make clean && npm run build

运行测试:

# 完整测试
npm test

# 快速测试(跳过链接检查)
npm run test:fast

# 指定测试
npm run link-check

3. 内容开发

创建新内容:

# 博客
hugo new content/zh/blog/my-new-post.md

# 书籍章节
hugo new content/zh/book/my-book/chapter-1.md

# 播客
hugo new content/zh/podcast/episode-001.md

处理资源:

# 转换 Mermaid 图表
npm run transform-mermaid

# 添加图片尺寸
npm run add-image-dimensions

# 生成内容分析
npm run generate-analysis

高级配置

1. PostCSS 配置

项目使用 PostCSS 处理 CSS,配置文件为 postcss.config.js

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('@fullhuman/postcss-purgecss')({
      content: [
        './layouts/**/*.html',
        './content/**/*.md',
        './assets/js/*.js'
      ],
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
      safelist: [
        /^hljs/,
        /^mermaid/,
        /^markmap/,
        /^toast/
      ]
    })
  ]
};

2. Hugo 配置

主要开发设置在 config/_default/config.toml

# 开发设置
[params]
enable_comment = true
anchored = true
top_header = true

# 构建设置
[build]
postCSS = ["postcss.config.js"]

# 标记设置
[markup]
  [markup.goldmark]
    [markup.goldmark.renderer]
      unsafe = true
    [markup.goldmark.parser]
      wrapStandAloneImageWithinParagraph = false
      [markup.goldmark.parser.attribute]
        block = true
        image = true

3. 开发脚本

scripts/ 目录包含多种开发脚本:

脚本 作用 用法
build.js 生产构建与压缩 npm run build
generate-analysis-data.js 内容分析 npm run generate-analysis
transform-mermaid.js Mermaid 图表处理 npm run transform-mermaid
add-image-dimensions.js 图片优化 npm run add-image-dimensions
upload-images.js 图片上传 CDN npm run upload-images

性能优化

1. 开发服务器优化

Hugo 服务器参数:

# 快速开发服务器
hugo server --gc --minify

# 局域网访问
hugo server --bind 0.0.0.0 --baseURL http://[your-ip]:1313

# 生产环境模拟
hugo server --environment production

2. 构建优化

并行处理:

# 多核加速
export HUGO_NUMWORKERTHREADS=8
hugo --gc --minify

资源优化:

# 构建前优化图片
npm run add-image-dimensions

# 转换图表
npm run transform-mermaid

# 生成分析数据
npm run generate-analysis

3. 缓存策略

浏览器缓存:

# netlify.toml
[[headers]]
  for = "*.css"
  [headers.values]
    Cache-Control = "public, max-age=31536000"

[[headers]]
  for = "*.js"
  [headers.values]
    Cache-Control = "public, max-age=31536000"

故障排查

常见问题

Hugo 服务器无法启动

问题hugo server 启动失败

解决方法

  1. 检查 Hugo 版本
hugo version
# 输出需包含 "extended"
  1. 检查端口占用
lsof -i :1313
# 如有进程占用,先关闭
  1. 检查配置语法
hugo config
# 应无语法错误

Node.js 依赖问题

问题npm install 失败或依赖过期

解决方法

  1. 清理 npm 缓存
npm cache clean --force
rm -rf node_modules package-lock.json
npm install
  1. 升级 Node.js
nvm install 20
nvm use 20
  1. 检查全局包冲突
npm list -g --depth=0

Python 环境问题

问题:Python 脚本运行失败或依赖缺失

解决方法

  1. 重建虚拟环境
rm -rf venv
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
  1. 检查 Python 版本
python3 --version
# 应为 3.9 及以上

构建失败

问题npm run build 失败

解决方法

  1. 检查语法错误
hugo --gc --minify --verbose
  1. 清理 Hugo 缓存
rm -rf resources/ public/
  1. 检查 PostCSS 配置
npx postcss --version

调试模式

开启调试日志:

# Hugo 调试模式
hugo server --debug --verbose

# Node.js 调试模式
DEBUG=* npm run build

# Python 调试模式
PYTHONPATH=. python -m pdb scripts/build.py

性能分析

分析构建性能:

# Hugo 构建分析
hugo --templateMetrics --templateMetricsHints

# Node.js 分析
node --prof scripts/build.js
node --prof-process isolate-*.log > processed.txt

IDE 集成

VS Code 配置

启动配置(.vscode/launch.json):

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Hugo Server",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/.bin/hugo",
      "args": ["server", "--debug"],
      "console": "integratedTerminal"
    },
    {
      "name": "Debug Build Script",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/scripts/build.js",
      "console": "integratedTerminal"
    }
  ]
}

任务配置(.vscode/tasks.json):

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Hugo Server",
      "type": "shell",
      "command": "hugo server",
      "group": "build",
      "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
      }
    },
    {
      "label": "Build Production",
      "type": "shell",
      "command": "npm run build",
      "group": "build"
    }
  ]
}

后续步骤

完成开发环境设置后:

相关主题


需要帮助?请查阅故障排查指南或在 GitHub 提交 issue。