node 生成 html 模板替换

参考:

https://cloud.tencent.com/developer/news/310776

https://gitlab.com/wheresvic/software-dawg/-/tree/master/src

安装

npm init
npm i --save-exact bluebird chokidar fs-extra mustache
mkdir src
mkdir public

添加index.js

复制代码
const Promise = require("bluebird");
const path = require("path");
const fs = Promise.promisifyAll(require("fs"));
const fse = require("fs-extra");
const Mustache = require("mustache");
const chokidar = require("chokidar");


// 运行程序
Promise.resolve().then(async () => {
  await main();
});

const env = process.env.NODE_ENV || "dev";

const main = async () => {
  console.log("Running app in " + env)
  await generateSite();
  if (env === "dev") {
    watchFiles()
  }
};

const generateSite = async () => {
  await copyAssets();
  await buildContent();
};

// 清空生成文件夹,复制静态文件
const copyAssets = async () => {
  await fse.emptyDir("public");
  await fse.copy("src/pages/res", "public/res");
};

// 监听文件更改
const watchFiles = () => {
  const watcher = chokidar.watch(
    ["src"], {
    ignored: '/(^|[/\])../',
    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();
  });
};

// 使用 Mustache 渲染
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;
    // 跳过静态文件
    if(name == 'res'){
      continue;
    }
    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.writeFileSync(path.join("public", page + ".html"), pages[page]);
  }
};
复制代码

目录结构像这样

 

src中是源文件,public是生成文件,res是静态文件夹,只会全部复制,partials中是要替换的字符串,后缀是 .mst

用法是在pages中的html文件加上

  {{> footer}}

就可以了

 

posted @   jqynr  阅读(97)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示