marked.js是一個(gè)可以在線(xiàn)轉(zhuǎn)碼Markdown的JavaScript編寫(xiě)的庫(kù)卵惦∪悍觯可以非常方便的在線(xiàn)編譯Markdown代碼為HTML并直接顯示,并且支持完全的自定義各種格式粹胯。
項(xiàng)目地址:https://github.com/chjj/marked
安裝
使用npm
則可以直接安裝:
npm install marked --save
使用
1. 使用示例
簡(jiǎn)單的使用示例:
var marked = require('marked');
console.log(marked('I am using __markdown__.'));
// Outputs: <p>I am using <strong>markdown</strong>.</p>
使用默認(rèn)值設(shè)置選項(xiàng)的示例:
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頁(yè)面使用示例:
<!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類(lèi)型 - 要編譯的markdown源碼收毫。 -
options
object類(lèi)型 - 選項(xiàng),也可以使用marked.setOptions
方法設(shè)置谓媒。 -
callback
function類(lèi)型 - 當(dāng)markdownString
已經(jīng)被完全的異步解析完畢會(huì)調(diào)用這個(gè)函數(shù)淆院。如果options
參數(shù)被省略,這個(gè)可以作為第二個(gè)參數(shù)句惯。
3. 選項(xiàng)
highlight
function類(lèi)型
代碼高亮的回調(diào)函數(shù)土辩。下面的第一個(gè)例子使用node-pygmentize-bundled的異步高亮,第二個(gè)例子使用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類(lèi)型 - 傳給highlighter的代碼塊抢野。 -
lang
string類(lèi)型 - 代碼塊中指定的編程語(yǔ)言拷淘。 -
callback
function類(lèi)型 - 當(dāng)使用一個(gè)異步highlighter時(shí)要調(diào)用這個(gè)回調(diào)函數(shù)。
renderer
object類(lèi)型 - 默認(rèn)為new Renderer()
指孤。
一個(gè)Object启涯,包含了渲染為HTML的函數(shù)。
重寫(xiě)renderer方法
renderer
選項(xiàng)允許你使用自定義樣式進(jìn)行渲染恃轩。這里有一個(gè)重寫(xiě)標(biāo)題標(biāo)記渲染的例子结洼,渲染成像GitHub一樣添加一個(gè)嵌入式錨標(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 }));
這個(gè)代碼將會(huì)輸出下面的HTML:
<h1>
<a name="heading-" class="anchor" href="#heading-">
<span class="header-link"></span>
</a>
heading+
</h1>
塊級(jí)元素渲染方法
- 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類(lèi)型 - 默認(rèn)為true
開(kāi)啟GitHub flavored markdown肪获。
tables
boolean類(lèi)型 - 默認(rèn)為true
開(kāi)啟GFM tables碌更。這個(gè)選項(xiàng)要求gfm
選項(xiàng)被設(shè)置為true
试躏。
breaks
boolean類(lèi)型 - 默認(rèn)為false
開(kāi)啟GFM line breaks尝盼。這個(gè)選項(xiàng)要求gfm
選項(xiàng)被設(shè)置為true
。
pedantic
boolean類(lèi)型 - 默認(rèn)為false
模糊部分盡可能的遵循markdown.pl
氮发。不修復(fù)原始的markdown中的bug或poor behavior盆犁。
sanitize
boolean類(lèi)型 - 默認(rèn)為false
輸出審查肚邢。忽略任何輸入的HTML酥艳。
smartLists
boolean類(lèi)型 - 默認(rèn)為true
Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic
.
smartypants
boolean類(lèi)型 - 默認(rèn)為false
Use "smart" typograhic punctuation for things like quotes and dashes.
4. 訪(fǎng)問(wèn)lexer和parser
如果你愿意摊溶,你可以直接訪(fǎng)問(wèn)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語(yǔ)言編寫(xiě)的一個(gè)轉(zhuǎn)換器玖雁,Marked現(xiàn)在比Discount還要快更扁。
對(duì)于那些感到懷疑的:這些基準(zhǔn)運(yùn)行全部的markdown測(cè)試組件1000次盖腕。測(cè)試組件測(cè)試每個(gè)功能赫冬,并沒(méi)有單獨(dú)的偏向于某個(gè)特定的方面浓镜。
Pro level
如果你愿意,你可以直接訪(fǎng)問(wèn)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. 運(yùn)行測(cè)試以及貢獻(xiàn)
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àn)與許可協(xié)議
如果你向該項(xiàng)目貢獻(xiàn)代碼膛薛,則默認(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.