wechat-markdown-html
v2.0.6
Published
将 Markdown 转换为可直接粘贴到公众号编辑器的 HTML 片段,内联主题样式与代码高亮。
Maintainers
Readme
wechat-markdown-html
将 Markdown 一键转为可直接粘贴到微信公众号编辑器的 HTML 正文片段,内联主题样式并内置代码高亮、目录、脚注、Ruby 注音等能力。
安装
npm i wechat-markdown-html快速开始
import { markdownToHtml } from "wechat-markdown-html";
const markdown = "# 标题\n\n这是正文";
const htmlFragment = markdownToHtml(markdown);
console.log(htmlFragment);API
markdownToHtml(markdown, options)
- markdown: string
- options: MarkdownToHtmlOptions
返回可直接粘贴到公众号编辑器的正文片段(不含 html/head/body)。
markdownToWebHtml(markdown, options)
- markdown: string
- options: MarkdownToWebOptions
返回完整 Web 文档(包含 html/head/body),带左右侧边栏目录与当前章节子目录。
MarkdownToHtmlOptions
- theme: StyleFile | string(默认 "nature-green")
- codeTheme: CodeTheme(默认 "wechat")
- macStyle: boolean(默认 false)
- fontSize: number(设置正文字号,单位 px)
- extraCss: string
- sanitize: boolean(默认 true)
MarkdownToWebOptions
在 MarkdownToHtmlOptions 基础上新增:
- title: string(页面标题)
- sanitize: boolean(默认 false,保留脚本以支持 Web 侧边栏联动)
其他导出
- styleFiles:可用主题列表
- codeThemes:可用代码主题列表
- getStylePath(styleFile):返回主题相对路径
- getThemeCss(styleFile):返回主题 CSS 字符串
- markdownToWebHtml:生成完整 Web 文档
主题与代码主题
可用主题输入值:
nature-green(自然绿)warm-orange(暖橙)minimalist-black(极简黑)noble-purple(高贵紫)soft-gray(柔灰)fresh-green(清新绿)vibrant-red(鲜红)standard-gray(标准灰)ocean-blue(海洋蓝)tech-blue(科技蓝)serene-teal(静谧青)golden-amber(金琥珀)mountain-blue(山峦蓝)geek-black(极客黑)pure-white(纯白)lavender-purple(薰衣草紫)sky-blue(天空蓝)
可用 CodeTheme:
wechat(微信代码风格)atom-one-dark(原子一号·暗)atom-one-light(原子一号·亮)monokai(Monokai)github(GitHub)vs2015(VS2015)xcode(Xcode)
特殊语法
目录
在文中放置 [TOC],渲染为二、三级标题的目录区块。
脚注
非微信链接(非 mp.weixin.qq.com、非 # 与 / 开头)会自动转为脚注,正文显示为带上标的文字,链接汇总在文末“引用链接”区块。
Ruby 注音
使用 {文本|拼音},例如 {汉字|hàn zì}。
横向滑动图片组
单行尖括号包裹多图,逗号分隔:
<, >安全清理
sanitize 为 true 时会进行基础清理:
- 移除 script 标签
- 移除内联事件(如 onclick)
- 将 javascript: 协议替换为 #
示例脚本
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { markdownToHtml, markdownToWebHtml, styleFiles } from "wechat-markdown-html";
const markdownPath = resolve(process.cwd(), "examples", "basic.md");
const markdown = readFileSync(markdownPath, "utf8");
const theme = "nature-green";
const codeTheme = "wechat";
const htmlFragment = markdownToHtml(markdown, {
theme,
codeTheme,
macStyle: true,
sanitize: true
});
const webHtml = markdownToWebHtml(markdown, {
theme,
codeTheme,
macStyle: true,
title: "Markdown Preview"
});
const outputPath = resolve(process.cwd(), "examples", "output.html");
const outputWebPath = resolve(process.cwd(), "examples", "output-web.html");
writeFileSync(outputPath, htmlFragment, "utf8");
writeFileSync(outputWebPath, webHtml, "utf8");
console.log(`示例主题: ${theme}`);
console.log(`可用主题数量: ${styleFiles.length}`);
console.log(`输出文件: ${outputPath}`);
console.log(`输出 Web 文件: ${outputWebPath}`);
console.log(`输出格式: 仅正文片段(可直接粘贴公众号编辑器)`);