答案:JavaScript 驱动的静态站点生成器通过 Node.js 读取模板与内容,利用字符串替换或 Markdown 解析渲染 HTML,再批量输出文件。核心流程为:设计 content、templates、public 目录结构;使用 fs 模块读写文件;通过简单模板引擎替换 {{key}} 插值;借助 marked 库将 Markdown 转为 HTML;遍历内容文件批量生成页面;可额外构建首页聚合链接。关键点包括路径处理、错误捕获与输出清理,后续可扩展 Front Matter、CSS 注入等功能。整个过程不依赖框架,突出轻量与可控性。

实现一个 JavaScript 驱动的静态站点生成器(SSG)并不需要依赖复杂的框架。核心思路是:用 Node.js 读取模板和内容文件,通过 JavaScript 处理数据并渲染 HTML,最后输出静态文件到指定目录。
一个最简 SSG 包含以下几个部分:
利用 fs 和 path 模块处理文件系统操作:
const fs = require('fs');
const path = require('path');
function readFile(filePath) {
return fs.readFileSync(filePath, 'utf-8');
}
function writeFile(filePath, content) {
fs.writeFileSync(filePath, content);
console.log(`已生成: ${filePath}`);
}
可以使用简单的字符串替换实现模板引擎:
立即学习“Java免费学习笔记(深入)”;
function renderTemplate(template, data) {
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
return data[key] || match;
});
}
例如模板 <h1>{{title}}</h1>,传入 { title: "首页" } 后会替换为实际标题。
安装 marked 解析 Markdown:
npm install marked
在构建脚本中使用:
const { marked } = require('marked');
const mdContent = readFile('content/post1.md');
const htmlContent = marked.parse(mdContent);
以生成一篇文章为例:
const template = readFile('templates/post.html');
const content = readFile('content/post1.md');
const data = {
title: '我的第一篇文章',
content: marked.parse(content)
};
const html = renderTemplate(template, data);
writeFile('public/post1.html', html);
遍历 content 目录自动生成所有文章:
fs.readdirSync('content').forEach(file => {
if (path.extname(file) === '.md') {
const slug = path.basename(file, '.md');
const content = readFile(`content/${file}`);
const html = marked.parse(content);
const page = renderTemplate(template, {
title: `关于 ${slug}`,
content: html
});
writeFile(`publichttps://www.php.cn/link/eb22f88f11afb43e5ad8075fc7b2491e`, page);
}
});
可以额外生成一个首页,列出所有文章链接:
let links = '';
fs.readdirSync('content').forEach(file => {
const slug = path.basename(file, '.md');
links += `<li><a href="https://www.php.cn/link/eb22f88f11afb43e5ad8075fc7b2491e">${slug}</a></li>`;
});
const homeHtml = renderTemplate(homeTemplate, { links });
writeFile('public/index.html', homeHtml);
以上就是如何实现一个JavaScript驱动的静态站点生成器(SSG)?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号