网站上的文字可能来自 Markdown、JSON、数据库或模板。先找到来源,再改生成结果。本练习只改一篇文章的标题和摘要,保留 slug、正文及链接。
练习项目可以从两个文件建起来
在新的 demo-content 目录安装 Node.js 依赖:先运行 npm init -y,再运行 npm install gray-matter markdown-it。依赖只装在练习目录,已有项目按自己的锁文件与构建命令执行。
新建 content/guide.md:
---
title: 文件整理大全
description: 全面提高效率的好方法。
slug: file-guide
---
## 为什么先查引用
移动图片前先找使用它的页面;每一处相对路径应按来源文件所在目录计算。
## 本例只移动两张图
列出旧路径、新路径、引用来源和恢复记录,完成后重开两个入口页面。
新建 build.mjs,完整内容:
import fs from 'node:fs';
import matter from 'gray-matter';
import MarkdownIt from 'markdown-it';
const md=new MarkdownIt({html:false});
const escape=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const {data,content}=matter(fs.readFileSync('content/guide.md','utf8'));
for(const k of ['title','description','slug']) {
if(typeof data[k]!=='string'||!data[k].trim())throw Error('Missing '+k);
}
if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(data.slug))throw Error('Invalid slug');
const shell=(title,description,body)=>'<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'+escape(title)+'</title><meta name="description" content="'+escape(description)+'"></head><body>'+body+'</body></html>';
const article=shell(data.title,data.description,'<h1>'+escape(data.title)+'</h1>'+md.render(content));
const index=shell('文章目录','现有操作指南','<h1>文章目录</h1><a href="'+data.slug+'.html">'+escape(data.title)+'</a><p>'+escape(data.description)+'</p>');
fs.mkdirSync('dist',{recursive:true});
fs.writeFileSync('dist/'+data.slug+'.html',article);
fs.writeFileSync('dist/index.html',index);
console.log('Built '+data.slug+'.html and index.html');
运行 node build.mjs。此时 dist/file-guide.html 与 dist/index.html 都应出现旧标题。这个小程序仅演示来源关系;真实项目仍复用自己的模板、导航和公共底栏。
让 Codex 沿着字符串找源
有 ripgrep 时可执行 rg -n "文件整理大全" content build.mjs dist;没有则用编辑器全项目搜索。命中两个输出文件和一个 Markdown 并不代表三个地方都要改,build.mjs 的读取关系说明 content/guide.md 才是源。
读取 demo-content 的 build.mjs、content/guide.md 及生成页。
把文章 title 改成“整理项目图片:先查引用,再迁移两张截图”;
description 改成“用旧新路径映射移动两张截图,同步更新两处引用,并保留恢复记录。”
只改源 frontmatter 的这两项;不改 slug、正文、构建器和其他文件。
运行本项目构建,在生成文章与目录中核对 title、description、H1 和卡片文案。
交付源 diff、执行命令、实际输出路径和未完成检查;不要仅手改 dist。
如果 Codex 发现真实项目还有 title/navTitle/SEO 标题分离,应先列字段消费者,再只调整目标字段。本练习只有一个 title,所以文章 title、H1、卡片标题会一起变。
对照输出位置,而不是搜索命中数量
| 输出位置 | 应出现的内容 |
|---|---|
| file-guide.html / title、H1 | 新标题 |
| file-guide.html / meta description | 新摘要 |
| index.html / 链接文字、卡片段落 | 新标题、新摘要 |
| index.html / href | 仍为 file-guide.html |
| content/guide.md / 正文 | 原两段内容 |
若只改 dist/index.html,下一次 node build.mjs 会重新读取旧 frontmatter,覆盖那次手改。若改对源但页面未更新,应先看构建是否成功、查看的是否同一个 dist、浏览器缓存是否仍是旧版,不能反复改更多位置碰碰运气。
恢复这次内容修改时,只还原 Markdown 的两项字段并重建;后来新增的正文不应被整文件旧备份覆盖。本页的构建日志是读者需要获得的结果,不代表任何线上站点已经发布。
下一步
继续阅读与你当前问题相关的教程:


