最新消息:看到那些跳动的图片、文字了吗?点击点击 O(∩_∩)O~~

Node.js 转换 Markdown 并且语法高亮

开发工具 onlyling 4719浏览

最近写了一些小东西,用到了 Markdown 作为文档编辑,并且显示到了页面上。

Markdown

Markdown 的目标是实现「易读易写」。

可读性,无论如何,都是最重要的。一份使用 Markdown 格式撰写的文件应该可以直接以纯文本发布,并且看起来不会像是由许多标签或是格式指令所构成。Markdown 语法受到一些既有 text-to-HTML 格式的影响,包括 SetextatxTextilereStructuredTextGrutatextEtText,而最大灵感来源其实是纯文本电子邮件的格式。

点击查看语法

本文也使用 Markdown 编辑

marked

A full-featured markdown parser and compiler, written in JavaScript. Built for speed.

一个可以在服务器端、浏览器端使用的转换库,简单、易用。

点击查看文档

highlight.js

Highlight.js is a syntax highlighter written in JavaScript. It works in the browser as well as on the server. It works with pretty much any markup, doesn’t depend on any framework and has automatic language detection.

点击查看文档

如何使用

普通文本

Node.js转换文件

var marked = require('marked');
var markdownString = '```js\n console.log("hello"); \n```';
var HTMLString = marked(markdownString);

页面

<link href="https://cdn.bootcss.com/github-markdown-css/2.8.0/github-markdown.min.css" rel="stylesheet">

<div class="markdown-body">
    {{HTMLString}}
</div>

代码高亮

Node.js转换文件

var marked = require('marked');

// 同步使用 highlight.js 转换代码
marked.setOptions({
    highlight: function (code) {
        return require('highlight.js').highlightAuto(code).value
    }
})

var markdownString = '```js\n console.log("hello"); \n```';
var HTMLString = marked(markdownString);

页面

<link href="https://cdn.bootcss.com/github-markdown-css/2.8.0/github-markdown.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/github-gist.min.css" rel="stylesheet">

<div class="markdown-body">
    {{HTMLString}}
</div>

Markdown、代码高亮样式

这里使用的是 github-markdown-css 样式库,可以根据自己的喜好修改。

代码高亮用的是 github-markdown 样式库,两个加起来就是活脱脱的 GitHub 风格。

highlight.js 有很多不同的风格,可以在这里查看。

转载请注明:OnlyLing - Web 前端开发者 » Node.js 转换 Markdown 并且语法高亮