Metalsmith 静态站点实战:解析 static-site 示例的完整构建流程

原创2026-10-14 12:53:381,879 阅读
文章标签:开发工具CLI前端

Metalsmith 静态站点实战:解析 static-site 示例的完整构建流程

Metalsmith 是一款"极其简单、可插拔"的 Node.js 静态站点生成器,核心思想是"所有逻辑都由插件处理,只需将它们链式组合"。本篇文章以仓库中的 examples/static-site 官方示例为蓝本,从运行命令、构建脚本、目录结构、布局模板到底层 API 实现,完整拆解一个带博客列表功能的静态站点是如何从 Markdown 源文件一步步变成可部署的 HTML 站点的。读完后你将掌握 Metalsmith 的 metadata、source、destination、clean、use、build 等核心 API 的用法,以及 collections、markdown、permalinks、layouts 四大官方插件的协作模式,可以直接照搬这套结构搭建自己的个人博客或文档站。

一、示例概览:三行命令跑起来

原文档 examples/static-site/README.md 给出了最直接的体验路径——克隆仓库后进入示例目录,安装依赖并启动构建:

npm install
npm start

构建完成后,在浏览器里预览生成的站点:

npm run serve

其中 npm start 实际执行的是 node index.js(即运行构建脚本),npm run serve 执行的是 serve build(即用静态服务器托管构建产物目录)。这些脚本定义在 examples/static-site/package.json 中:

{
  "name": "static-site-example",
  "private": true,
  "dependencies": {
    "jstransformer-handlebars": "^1.2.0",
    "metalsmith": "^2.5.0",
    "@metalsmith/collections": "^1.2.1",
    "@metalsmith/layouts": "^2.5.1",
    "@metalsmith/markdown": "^1.5.0",
    "@metalsmith/permalinks": "^2.4.0"
  },
  "devDependencies": {
    "serve": "^13.0.2"
  },
  "scripts": {
    "start": "node index.js",
    "serve": "serve build"
  }
}

值得注意的依赖细节:

  • metalsmith 是本仓库的核心包(当前版本 2.7.0,见 package.json 与 lib/index.js),本示例声明 ^2.5.0;
  • @metalsmith/markdown、@metalsmith/layouts、@metalsmith/collections、@metalsmith/permalinks 是官方核心插件,分别负责 Markdown 转 HTML、套用布局模板、文章分组、URL 美化;
  • jstransformer-handlebars 是 Handlebars 的 jstransformer 适配器,为 @metalsmith/layouts 提供模板引擎支持;
  • serve 只是一个轻量静态文件服务器,仅用于本地预览。

示例的完整目录结构如下:

examples/static-site/
├── index.js          # 构建脚本(入口)
├── package.json      # 依赖与 npm 脚本
├── layouts/
│   ├── layout.hbs    # 通用页面布局模板
│   └── post.hbs      # 博客文章布局模板
└── src/
    ├── index.md      # 首页(含博客列表)
    ├── about.md      # 关于页
    ├── css/
    │   └── style.css # 站点样式
    └── posts/
        ├── first-post.md
        ├── second-post.md
        ├── third-post.md
        └── fourth-post.md

二、构建脚本逐行解析:index.js 的完整 API 链

构建的核心逻辑全部集中在 examples/static-site/index.js 这一个文件中。它完整演示了 Metalsmith 的典型用法,下面逐段拆解。

2.1 引入核心与插件

const Metalsmith = require('metalsmith')
const markdown = require('@metalsmith/markdown')
const layouts = require('@metalsmith/layouts')
const permalinks = require('@metalsmith/permalinks')
const collections = require('@metalsmith/collections')

五个模块职责分明:Metalsmith 是构建器本体,其余四个是官方插件,每个插件都是一个工厂函数,调用后返回真正的插件函数。

2.2 初始化并注入全局元数据

Metalsmith(__dirname)
  .metadata({
    sitename: 'My Static Site & Blog',
    description: "It's about saying »Hello« to the World.",
    generator: 'Metalsmith',
    url: 'https://metalsmith.io/'
  })

Metalsmith(__dirname) 将当前目录设为工作目录。从 lib/index.js 的构造函数可以看到,核心在初始化时会设置一组默认值:source('src')、destination('build')、concurrency(Infinity)、clean(true)、frontmatter(true),这也解释了示例脚本为什么可以只显式配置部分选项。

.metadata({...}) 设置全局元数据。这些数据会进入每个文件对象,供布局模板直接取用——{{ sitename }}、{{ description }}、{{ generator }}、{{ url }} 在模板中就是这样被渲染的。底层实现见 lib/index.js:传入对象会通过 Object.assign 合并进已有元数据,且该方法可多次调用。

2.3 配置源目录、目标目录与清理策略

  .source('./src')
  .destination('./build')
  .clean(true)
  • .source('./src'):指定从 src 目录读取源文件;
  • .destination('./build'):指定把构建结果写入 build 目录;
  • .clean(true):每次构建前先清空 build 目录,保证产物干净无残留。

clean 的默认值就是 true(构造函数中 this.clean(true) 已确认,同时测试 test/index.js 也断言了默认行为),示例中显式写出是为了可读性。对应 API 实现可查看 lib/index.js(source/destination 的 getter-setter 二合一设计)与 lib/index.js(clean)。构建流程中,build 方法在插件处理完成后会先 rm(dest) 清空目标目录再写入,见 lib/index.js。

2.4 插件链:collections → markdown → permalinks → layouts

  .use(
    collections({
      posts: 'posts/*.md'
    })
  )
  .use(markdown())
  .use(permalinks())
  .use(
    layouts({
      engineOptions: {
        helpers: {
          formattedDate: function (date) {
            return new Date(date).toLocaleDateString()
          }
        }
      }
    })
  )

这是整个示例的核心,四条 .use() 按顺序组成一个插件流水线。use 的实现非常简单——把插件函数推入数组并返回自身(lib/index.js),真正执行时按数组顺序依次调用(run 方法在 lib/index.js 中通过 ware 库串行运行)。

  1. collections(文章分组):{ posts: 'posts/*.md' } 把所有匹配 posts/*.md 的文件聚合成一个名为 posts 的集合,挂到全局 metadata 上。模板中的 {{#each posts}} 即来源于此。
  2. markdown(Markdown 转 HTML):将每篇 *.md 的 contents 从 Markdown 编译为 HTML。
  3. permalinks(永久链接):默认规则下把 posts/first-post.md 这类路径改写成 posts/first-post/index.html 的目录式 URL(对应布局模板里的 /{{ path }} 链接形式),同时把 contents 重命名为 index.html。
  4. layouts(套用布局):把 contents 注入到 frontmatter 指定的布局模板中。这里通过 engineOptions.helpers 注册了一个名为 formattedDate 的 Handlebars 辅助函数,将 new Date(date).toLocaleDateString() 的结果渲染到模板——post.hbs 中的 {{ formattedDate date }} 就是它的调用点。

2.5 触发构建

  .build(function (err, files) {
    if (err) throw err
  })

.build(callback) 执行完整构建:读取源文件 → 运行插件链 → 清理目标目录 → 写回磁盘。回调收到 (err, files),其中 files 是构建完成后的全部文件对象。build 同时支持回调风格与 Promise 风格(无回调时返回 Promise),见 lib/index.js。

三、内容组织:src 目录与 frontmatter 元数据

3.1 首页:声明布局并启用博客列表

src/index.md 是站点的首页源文件:

---
title: Hello World
layout: layout.hbs
postlist: true
---

This site is about saying »Hello« to the world.

# Blog

Read what else I have to say. Here are all my blog posts. Enjoy reading!

frontmatter(文件头部由 --- 包裹的 YAML 块)中的 title、layout、postlist 会被解析为文件对象的元数据。layout: layout.hbs 告诉 layouts 插件套用哪个模板,postlist: true 则是 layout.hbs 中 {{#if postlist}} 的判断开关——首页因此会渲染出博客文章列表,而关于页不会。

3.2 博客文章:frontmatter 驱动的完整示例

以 src/posts/first-post.md 为例:

---
title: My First Post
date: 2012-08-20
layout: post.hbs
---

An interesting post about how it's going to be different this time around. I'm going to write a lot more nowadays and use this blog to improve my writing.

其余三篇文章(second-post.md、third-post.md、fourth-post.md)结构相同,title、date、layout 是博客场景最常见的三个字段:title 用于模板中的 <title> 和链接文本,date 被 formattedDate 辅助函数格式化后显示在文章页头部,layout: post.hbs 让文章使用专门的文章模板。

3.3 关于页

src/about.md 声明了 layout: layout.hbs 与 title: About,并刻意设置了 description: ''(空字符串)覆盖全局描述,演示了"文件级元数据覆盖全局元数据"的机制——这也是为什么 layout.hbs 里 {{ description }} 在各页面会得到不同输出。

3.4 底层原理:frontmatter 是如何被解析的

frontmatter 解析由核心库完成。Metalsmith 构造函数内置了一个 Matter 实例(lib/index.js),其 parse 方法在 lib/matter.js 中实现:底层委托给 gray-matter,默认选项为 YAML 语言、--- 定界符、关闭 excerpt(见 lib/matter.js)。解析结果中,frontmatter 键值会展开成文件对象的顶层属性,正文部分则存入 contents(一个 Buffer)。

读取文件的完整路径是:build → process → read(lib/index.js)→ readFile(lib/index.js)。readFile 中只有在前置元数据开关开启且文件为 UTF-8 编码时才调用 matter.parse,否则直接把原始内容放入 contents。测试 test/index.js 对 excerpt 解析行为有专门断言,test/fixtures/read-frontmatter/src/index.md 则是 frontmatter 解析的最小夹具。若希望文件跳过 frontmatter 解析,可用 .frontmatter(false) 关闭(API 见 lib/index.js)。

四、布局模板:Handlebars 下的变量注入与列表渲染

4.1 通用布局 layout.hbs

layouts/layout.hbs 是首页和关于页共用的模板,核心片段如下:

<title>{{ sitename }} &mdash; {{ title }}</title>
<meta name="description" content="{{ description }}">
...
<h1>{{ title }}</h1>

<main>
  {{{ contents }}}
  {{#if postlist}}
    <ul>
    {{#each posts}}
      <li>
        <a href="/{{ path }}">{{ title }}</a>
      </li>
    {{/each}}
    </ul>
  {{/if}}
</main>

<footer>
  <p>Generated with {{ generator }} &mdash; <a href="{{ url }}">{{ url }}</a></p>
</footer>

模板中三类数据一目了然:

  • 全局元数据:{{ sitename }}、{{ description }}、{{ generator }}、{{ url }} 来自 .metadata({...});
  • 文件级元数据:{{ title }}、{{ postlist }}、{{ path }} 来自每个文件的 frontmatter 或 permalinks 插件写入的路径信息;
  • 集合数据:{{#each posts}} 遍历 collections 插件生成的 posts 集合,为每篇文章输出一个指向 /{path} 的链接;
  • 三花括号 {{{ contents }}}:输出 HTML 正文而不做 HTML 转义(这是 Markdown 编译结果能被正确渲染的关键)。

4.2 文章模板 post.hbs

layouts/post.hbs 在通用骨架之上,把日期放在标题右侧:

<h1>{{ title }}<time class="float-right">{{ formattedDate date }}</time></h1>

这里 formattedDate 正是 index.js 中通过 layouts({ engineOptions: { helpers: ... } }) 注册的自定义辅助函数,演示了"模板引擎自定义 helper"的标准接入方式:任何合法的 JS 函数都能注册进模板环境。

4.3 样式文件

src/css/style.css 定义容器宽度、页头、页脚、正文与时间的简单样式,配合 layout.hbs 中引入的 Bootstrap 4 CSS(<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">)完成基础排版。

五、构建产物:permalinks 后的目录式 URL

在 .use(permalinks()) 与 layouts 插件的共同作用下,src/posts/first-post.md 最终会输出为 build/posts/first-post/index.html,而不是 build/posts/first-post.html。这正是布局中 <a href="/{{ path }}"> 能生成 /posts/first-post 这类干净 URL 的原因——permalinks 插件改写了文件路径,让每个页面拥有独立的目录式访问地址,是博客场景下最受欢迎的默认行为之一。

作为对照,仓库中的 examples/jekyll/metalsmith.json 与 examples/wintersmith/metalsmith.json 展示了 permalinks 的更多配置形态(如 "pattern": ":title"),可以进一步扩展对 URL 规则的理解。

六、从 API 到 CLI:同一套配置的另一种写法

本示例走的是 JavaScript API 路线,而 Metalsmith 同时提供 CLI 能力:将同样的配置写成 metalsmith.json,运行 metalsmith 命令即可完成构建(见 README.md)。配置文件中 source、destination、concurrency、metadata、clean、frontmatter 均为被识别选项,插件以数组形式声明。README 中明确把 examples/static-site 列为"简单静态站点生成器"的参考示例(README.md),并推荐与 Jekyll 示例对照学习 CLI 用法(README.md)。两者的本质一致:JS API 中 .metadata({...}) 对应配置文件的 metadata 字段,.use(plugin()) 对应 plugins 数组。

七、小结

通过 examples/static-site 这个官方示例,一条完整的 Metalsmith 工作链路已经清晰呈现:

  1. 读取:read 递归扫描 src,对每个文件解析 frontmatter(lib/matter.js),生成带元数据的文件对象;
  2. 加工:collections 聚合文章 → markdown 编译正文 → permalinks 生成目录式 URL → layouts 套用 Handlebars 模板并注入全局/文件级元数据;
  3. 写出:clean(true) 清空 build 后写入最终 HTML。

这种"核心只做文件读写、一切逻辑交给插件"的设计(见 README.md 对设计理念的阐述)让站点构建脚本可以短到一个文件、结构完全透明。照抄 index.js 的结构,替换 src 内容与布局模板,你就能在十几分钟内搭出第一个可部署的静态博客。

登录后查看全文
metalsmith