时间:2023-07-25 14:18:02 | 来源:网站运营
时间:2023-07-25 14:18:02 来源:网站运营
100行node.js搭建一个简单的静态站点生成器:最近我(作者 Victor Parmar)的一个同事想开一个博客,问我有没有什么建议。在研究了一些静态站点生成器和博客引擎后,我觉得 Hugo 是个很不错的选择。然而,我同事还有一些其它需求,比如想让博客都有自定义 URL 以及自定义 CSS 主题。虽然用 Hugo 也能实现这些要求,但是我还是决定跳过学习使用 Hugo 这部分,看看如果我同事已经有随时可用的 HTML 而且在 HTML 中写博客没有问题,能否创建一个很简单的静态站点生成器。npm initnpm i --save-exact bluebird chokidar fs-extra mustachemkdir srcmkdir public
const Promise = require("bluebird");const fse = require("fs-extra");Promise.resolve().then(async () => { await main();});const main = async() => { await generateSite();};const generateSite = async() => { await copyAssets();};const copyAssets = async() => { await fse.emptyDir("public"); await fse.copy("src", "public");};
const chokidar = require("chokidar");const main = async() => { await generateSite(); watchFiles();};const watchFiles = () => { const watcher = chokidar.watch( [ "src" ], { ignored: /(^|[////])/../, // chokidar will watch folders recursively ignoreInitial: false, persistent: true } ); watcher.on("change", async path => { console.log("changed " + path + ", recompiling"); await generateSite(); }); // catch ctrl+c event and exit normally process.on("SIGINT", function() { watcher.close(); });};
const env = process.env.NODE_ENV || "dev";const main = async () => { console.log("Running app in " + env); await generateSite(); if (env === "dev") { watchFiles(); }};
const fs = require("fs");const generateSite = async () => { await copyAssets(); await buildContent();};const buildContent = async () => { const pages = await compilePages(); await writePages(pages);};const compilePages = async () => { const partials = await loadPartials(); const result = {}; const pagesDir = path.join("src", "pages"); const fileNames = await fs.readdirAsync(pagesDir); for (const fileName of fileNames) { const name = path.parse(fileName).name; const fileContent = await fs.readFileAsync(path.join(pagesDir, fileName)); result[name] = Mustache.render(fileContent.toString(), {}, partials); } return result;};const loadPartials = async () => { const result = {}; const partialsDir = path.join("src", "partials"); const fileNames = await fs.readdirAsync(partialsDir); for (const fileName of fileNames) { const name = path.parse(fileName).name; const content = await fs.readFileAsync(path.join(partialsDir, fileName)); result[name] = content.toString(); } return result;};const writePages = async pages => { for (const page of Object.keys(pages)) { await fs.writeFileAsync(path.join("public", page + ".html"), pages[page]); }};
参考资料:
https://smalldata.tech/blog/2018/08/16/building-a-simple-static-site-generator-using-node-js
关键词:静态,成器,简单