JavaScript使用marked.js在線Markdown轉(zhuǎn)HTML

marked.js是一個可以在線轉(zhuǎn)碼Markdown的JavaScript編寫的庫??梢苑浅7奖愕脑诰€編譯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>

使用默認(rèn)值設(shè)置選項的示例:

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方法設(shè)置。
  • callback function類型 - 當(dāng)markdownString已經(jīng)被完全的異步解析完畢會調(diào)用這個函數(shù)。如果options參數(shù)被省略,這個可以作為第二個參數(shù)。

3. 選項

highlight

function類型

代碼高亮的回調(diào)函數(shù)。下面的第一個例子使用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類型 - 當(dāng)使用一個異步highlighter時要調(diào)用這個回調(diào)函數(shù)。

renderer

object類型 - 默認(rèn)為new Renderer()。

一個Object,包含了渲染為HTML的函數(shù)。

重寫renderer方法

renderer選項允許你使用自定義樣式進行渲染。這里有一個重寫標(biāo)題標(biāo)記渲染的例子,渲染成像GitHub一樣添加一個嵌入式錨標(biāo)簽的樣式:

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'
}

行內(nèi)元素渲染方法

  • 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類型 - 默認(rèn)為true

開啟GitHub flavored markdown

tables

boolean類型 - 默認(rèn)為true

開啟GFM tables。這個選項要求gfm選項被設(shè)置為true

breaks

boolean類型 - 默認(rèn)為false

開啟GFM line breaks。這個選項要求gfm選項被設(shè)置為true。

pedantic

boolean類型 - 默認(rèn)為false

模糊部分盡可能的遵循markdown.pl。不修復(fù)原始的markdown中的bug或poor behavior。

sanitize

boolean類型 - 默認(rèn)為false

輸出審查。忽略任何輸入的HTML。

smartLists

boolean類型 - 默認(rèn)為true

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

smartypants

boolean類型 - 默認(rèn)為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. 基準(zhǔn)

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語言編寫的一個轉(zhuǎn)換器,Marked現(xiàn)在比Discount還要快。

對于那些感到懷疑的:這些基準(zhǔn)運行全部的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

貢獻與許可協(xié)議

如果你向該項目貢獻代碼,則默認(rèn)你允許在MIT協(xié)議下分發(fā)你的代碼。You are also implicitly verifying that all code is your original work. </legalese>

9. 許可協(xié)議

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

See LICENSE for more info.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容