JavaScript使用marked.js在线Markdown转HTML

marked.js是一个可以在线转码Markdown的JavaScript编写的库。可以非常方便的在线编译Markdown代码为HTML并直接显示,并且支持完全的自定义各种格式。

项目地址:https://github.com/chjj/marked

安装

使用npm则可以直接安装:

npm install marked --save

使用

1. 使用示例

简单的使用示例:

var marked = require('marked');
console.log(marked('I am using __markdown__.'));
// Outputs: <p>I am using <strong>markdown</strong>.</p>

使用默认值设置选项的示例:

var marked = require('marked');
marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: true,
    smartypants: false
});

console.log(marked('I am using __markdown__.'));

在HTML页面使用示例:

<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Marked in the browser</title>
    <script src="lib/marked.js"></script>
</head>
<body>
    <div id="content"></div>
    <script>
        document.getElementById('content').innerHTML =
        marked('# Marked in browser\n\nRendered by **marked**.');
    </script>
</body>
</html>

2. 方法解析

marked(markdownString [,options] [,callback])

  • markdownString string类型 - 要编译的markdown源码。
  • options object类型 - 选项,也可以使用marked.setOptions方法设置。
  • callback function类型 - 当markdownString已经被完全的异步解析完毕会调用这个函数。如果options参数被省略,这个可以作为第二个参数。

3. 选项

highlight

function类型

代码高亮的回调函数。下面的第一个例子使用node-pygmentize-bundled的异步高亮,第二个例子使用highlight.js同步高亮:

var marked = require('marked');

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

// pygmentize-bundled的异步高亮
marked.setOptions({
    highlight: function (code, lang, callback) {
        require('pygmentize-bundled')({ lang: lang, format: 'html' }, code, function (err, result) {
            callback(err, result.toString());
        });
    }
});

// Using async version of marked
marked(markdownString, function (err, content) {
  if (err) throw err;
  console.log(content);
});

// highlight.js的同步高亮
marked.setOptions({
  highlight: function (code) {
    return require('highlight.js').highlightAuto(code).value;
  }
});

console.log(marked(markdownString));

highlight arguments

  • code string类型 - 传给highlighter的代码块。
  • lang string类型 - 代码块中指定的编程语言。
  • callback function类型 - 当使用一个异步highlighter时要调用这个回调函数。

renderer

object类型 - 默认为new Renderer()

一个Object,包含了渲染为HTML的函数。

重写renderer方法

renderer选项允许你使用自定义样式进行渲染。这里有一个重写标题标记渲染的例子,渲染成像GitHub一样添加一个嵌入式锚标签的样式:

var marked = require('marked');
var renderer = new marked.Renderer();

renderer.heading = function (text, level) {
    var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');

    return '<h' + level + '><a name="' +
                escapedText +
                 '" class="anchor" href="#' +
                 escapedText +
                 '"><span class="header-link"></span></a>' +
                  text + '</h' + level + '>';
},

console.log(marked('# heading+', { renderer: renderer }));

这个代码将会输出下面的HTML:

<h1>
    <a name="heading-" class="anchor" href="#heading-">
        <span class="header-link"></span>
    </a>
    heading+
</h1>

块级元素渲染方法

  • code(string code, string language)
  • blockquote(string quote)
  • html(string html)
  • heading(string text, number level)
  • hr()
  • list(string body, boolean ordered)
  • listitem(string text)
  • paragraph(string text)
  • table(string header, string body)
  • tablerow(string content)
  • tablecell(string content, object flags)

flags有下面的属性:

{
    header: true || false,
    align: 'center' || 'left' || 'right'
}

行内元素渲染方法

  • strong(string text)
  • em(string text)
  • codespan(string code)
  • br()
  • del(string text)
  • link(string href, string title, string text)
  • image(string href, string title, string text)

gfm

boolean类型 - 默认为true

开启GitHub flavored markdown

tables

boolean类型 - 默认为true

开启GFM tables。这个选项要求gfm选项被设置为true

breaks

boolean类型 - 默认为false

开启GFM line breaks。这个选项要求gfm选项被设置为true

pedantic

boolean类型 - 默认为false

模糊部分尽可能的遵循markdown.pl。不修复原始的markdown中的bug或poor behavior。

sanitize

boolean类型 - 默认为false

输出审查。忽略任何输入的HTML。

smartLists

boolean类型 - 默认为true

Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic.

smartypants

boolean类型 - 默认为false

Use "smart" typograhic punctuation for things like quotes and dashes.

4. 访问lexer和parser

如果你愿意,你可以直接访问lexer和parser。

var tokens = marked.lexer(text, options);
console.log(marked.parser(tokens));
var lexer = new marked.Lexer(options);
var tokens = lexer.lex(text);
console.log(tokens);
console.log(lexer.rules);

5. CLI

$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>

6. Philosophy behind marked

The point of marked was to create a markdown compiler where it was possible tofrequently parse huge chunks of markdown without having to worry aboutcaching the compiled output somehow...or blocking for an unnecesarily long time.
marked is very concise and still implements all markdown features. It is alsonow fully compatible with the client-side.
marked more or less passes the official markdown test suite in itsentirety. This is important because a surprising number of markdown compilerscannot pass more than a few tests. It was very difficult to get marked ascompliant as it is. It could have cut corners in several areas for the sakeof performance, but did not in order to be exactly what you expect in termsof a markdown rendering. In fact, this is why marked could be considered at adisadvantage in the benchmarks above.
Along with implementing every markdown feature, marked also implements GFMfeatures.

7. 基准

node v0.8.x

$ node test --bench
marked completed in 3411ms.
marked (gfm) completed in 3727ms.
marked (pedantic) completed in 3201ms.
robotskirt completed in 808ms.
showdown (reuse converter) completed in 11954ms.
showdown (new converter) completed in 17774ms.
markdown-js completed in 17191ms.

Discount是用C语言编写的一个转换器,Marked现在比Discount还要快。

对于那些感到怀疑的:这些基准运行全部的markdown测试组件1000次。测试组件测试每个功能,并没有单独的偏向于某个特定的方面。

Pro level

如果你愿意,你可以直接访问lexer和parser。

var tokens = marked.lexer(text, options);
console.log(marked.parser(tokens));
var lexer = new marked.Lexer(options);
var tokens = lexer.lex(text);
console.log(tokens);
console.log(lexer.rules);
$ node
> require('marked').lexer('> i am using marked.')
[ { type: 'blockquote_start' },
  { type: 'paragraph',
    text: 'i am using marked.' },
  { type: 'blockquote_end' },
  links: {} ]

8. 运行测试以及贡献

If you want to submit a pull request, make sure your changes pass the test suite. If you're adding a new feature, be sure to add your own test.

The marked test suite is set up slightly strangely: test/new is for all tests that are not part of the original markdown.pl test suite (this is where your test should go if you make one). test/original is only for the original markdown.pl tests. test/tests houses both types of tests after they have been combined and moved/generated by running node test --fix or marked --test --fix.

In other words, if you have a test to add, add it to test/new/ and then regenerate the tests with node test --fix. Commit the result. If your test uses a certain feature, for example, maybe it assumes GFM is not enabled, you can add .nogfm to the filename. So, my-test.text becomes my-test.nogfm.text. You can do this with any marked option. Say you want line breaks and smartypants enabled, your filename should be: my-test.breaks.smartypants.text.

To run the tests:

cd marked/
node test

贡献与许可协议

如果你向该项目贡献代码,则默认你允许在MIT协议下分发你的代码。You are also implicitly verifying that all code is your original work. </legalese>

9. 许可协议

Copyright (c) 2011-2014, Christopher Jeffrey. (MIT License)

See LICENSE for more info.

推荐阅读更多精彩内容