Back to Marked

USING ADVANCED

docs/USING_ADVANCED.md

18.0.316.4 KB
Original Source
<h2 id="instance">Marked instance</h2>

By default, Marked stores options and extensions in the global scope. That means changing the options in one script will also change the options in another script since they share the same instance.

If you don't want to mutate global scope, you can create a new instance of Marked to ensure options and extensions are locally scoped.

js
import { Marked } from 'marked';
const marked = new Marked([options, extension, ...]);
ArgumentTypeNotes
optionsobjectThe same arguments that can be passed to marked.use

Be careful: marked.use(...) should not be used in a loop or function. It should only be used directly after new Marked is created or marked is imported.

The parse function

js
import { marked } from 'marked';
marked.parse(markdownString [,options])
ArgumentTypeNotes
markdownStringstringString of markdown source to be compiled.
<a href="#options">options</a>objectHash of options. Can also use marked.use to set global options

Alternative using reference

js
// Create reference instance
import { marked } from 'marked';

// Set options
marked.use({
  async: true,
  pedantic: false,
  gfm: true,
});

// Compile
console.log(marked.parse(markdownString));
<h2 id="options">Options</h2>
MemberTypeDefaultSinceNotes
asyncbooleanfalse4.1.0If true, walkTokens functions can be async and marked.parse will return a promise that resolves when all walk tokens functions resolve.
breaksbooleanfalsev0.2.7If true, add `
on a single line break (copies GitHub behavior on comments, but not on rendered markdown files). Requiresgfmbetrue`.
gfmbooleantruev0.2.1If true, use approved GitHub Flavored Markdown (GFM) specification.
pedanticbooleanfalsev0.2.1If true, conform to the original markdown.pl as much as possible. Don't fix original markdown bugs or behavior. Turns off and overrides gfm.
rendererobjectnew Renderer()v0.3.0An object containing functions to render tokens to HTML. See extensibility for more details.
silentbooleanfalsev0.2.7If true, the parser does not throw any exception or log any warning. Any error will be returned as a string.
tokenizerobjectnew Tokenizer()v1.0.0An object containing functions to create tokens from markdown. See extensibility for more details.
walkTokensfunctionnullv1.1.0A function which is called for every token. See extensibility for more details.

Old Options

MemberTypeDefaultSinceNotes
smartLists (removed)booleanfalsev0.2.8Removed in v3.0.0.
baseUrl (removed)stringnullv0.3.9Removed in v8.0.0 use marked-base-url to prefix url for any relative link.
headerIds (removed)booleantruev0.4.0Removed in v8.0.0 use marked-gfm-heading-id to include an id attribute when emitting headings (h1, h2, h3, etc).
headerPrefix (removed)string''v0.3.0Removed in v8.0.0 use marked-gfm-heading-id to add a string to prefix the id attribute when emitting headings (h1, h2, h3, etc).
highlight (removed)functionnullv0.3.0Removed in v8.0.0 use marked-highlight to add highlighting to code blocks.
langPrefix (removed)string'language-'v0.3.0Removed in v8.0.0 use marked-highlight to prefix the className in a <code> block. Useful for syntax highlighting.
mangle (removed)booleantruev0.3.4Removed in v8.0.0 use marked-mangle to mangle email addresses.
sanitize (removed)booleanfalsev0.2.1Removed in v8.0.0 use a sanitize library, like DOMPurify (recommended), sanitize-html or insane on the output HTML!
sanitizer (removed)functionnullv0.3.4Removed in v8.0.0 use a sanitize library, like DOMPurify (recommended), sanitize-html or insane on the output HTML!
smartypants (removed)booleanfalsev0.2.9Removed in v8.0.0 use marked-smartypants to use "smart" typographic punctuation for things like quotes and dashes.
xhtml (removed)booleanfalsev0.3.2Removed in v8.0.0 use marked-xhtml to emit self-closing HTML tags for void elements (<br/>, <img/>, etc.) with a "/" as required by XHTML.
<h2 id="extensions">Known Extensions</h2>

Marked can be extended using custom extensions. This is a list of extensions that can be used with marked.use(extension).

<!-- Keep this list ordered alphabetically by name -->
NamePackage NameDescription
ABCjsabcjsABCjs sheet music rendering
Admonitionmarked-admonition-extensionAdmonition extension
Alertmarked-alertEnables GFM alerts
Base URLmarked-base-urlPrefix relative urls with a base URL
Bidimarked-bidiAdd Bidirectional text support to the HTML
CJK Breaksmarked-cjk-breaksSuppress soft linebreaks between east asian characters
Code Formatmarked-code-formatFormatting code blocks using Prettier
Code JSX Renderermarked-code-jsx-rendererRender JSX code blocks using a custom renderer and components
Code Previewmarked-code-previewTransform code blocks into code previews
Custom Heading IDmarked-custom-heading-idSpecify a custom heading id in headings with the Markdown Extended Syntax # heading {#custom-id}
Directivemarked-directiveSupports directives syntax
Emojimarked-emojiAdd emoji support like on GitHub
Extended Tablesmarked-extended-tablesExtends the standard Github-Flavored tables to support advanced features: Column Spanning, Row Spanning, Multi-row headers
Footnotemarked-footnoteEnables GFM footnotes
GFM Heading IDmarked-gfm-heading-idUse github-slugger to create the heading IDs and allow a custom prefix
Highlightmarked-highlightHighlight code blocks
HTML Renderermarked-html-rendererOutput HTML Elements instead of a string
Jira Renderermarked-jiraOutput Jira compatible format
Katex Codemarked-katex-extensionRender katex code
LinkifyItmarked-linkify-itUse linkify-it for urls
Manglemarked-mangleMangle mailto links with HTML character references
Marked Responsive Imagesmarked-responsive-imagesGenerate responsive (srcset) images based on structured filenames
Misskey-flavored Markdownmarked-mfmCustom extension for Misskey-flavored Markdown
More Listsmarked-more-listsSupport for alphabetical and roman numeral ordered lists
Plaintifymarked-plaintifyConverts Markdown to Plaintext
Shikimarked-shikiIntegrating Shiki syntax highlighting
Sequential Hooksmarked-sequential-hooksEnables the sequential preprocessing and post-processing within sequential hooks
Smartypantsmarked-smartypantsUse smartypants to use "smart" typographic punctuation for things like quotes and dashes
Smartypants litemarked-smartypants-liteA faster lighter version of marked-smartypants that doesn't use any external dependencies to create "smart" typographic punctuation for things like quotes and dashes
Token Positionmarked-token-positionAdds a position field to each token with start and end properties containing line, column, and offset
Typografmarked-typografUse typograf as a more powerful and extendable alternative to Smartypants for creating “smart” typographic punctuation, such as quotes and dashes
XHTMLmarked-xhtmlEmit self-closing HTML tags for void elements (<br/>, <img/>, etc.) with a "/" as required by XHTML
<h2 id="user-examples">User Examples</h2> <details> <summary>Marked can render on-page content as markdown in the browser.</summary>
html
<!DOCTYPE html>
<html>
 <head>
   <!-- Suggested stylesheet -->
   <link rel="stylesheet" 
    href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.8.1/github-markdown.min.css"
    crossorigin="anonymous" referrerpolicy="no-referrer" />

   <title>Marked for the full page</title>
 </head>

 <body> 
  <textarea id="markdown-source" style="display: none;">
# Title

Lots of text using **markdown syntax.**
  </textarea>
  <div id="content" class="markdown-body"></div>
  
  <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
  <script>
    const source = document.getElementById('markdown-source').value;
    
    // Parse the markdown and render it into the content div.
    document.getElementById('content').innerHTML = marked.parse(source);
  </script>
 </body>
</html>
</details> <h2 id="inline">Inline Markdown</h2>

You can parse inline markdown by running markdown through marked.parseInline.

js
const blockHtml = marked.parse('**strong** _em_');
console.log(blockHtml); // '<p><strong>strong</strong> <em>em</em></p>'

const inlineHtml = marked.parseInline('**strong** _em_');
console.log(inlineHtml); // '<strong>strong</strong> <em>em</em>'
<h2 id="highlight">Highlighting</h2>

Use marked-highlight to highlight code blocks.

<h2 id="workers">Workers</h2>

To prevent ReDoS attacks you can run marked on a worker and terminate it when parsing takes longer than usual.

Marked can be run in a worker thread on a node server, or a web worker in a browser.

Node Worker Thread

js
// markedWorker.js

import { marked } from 'marked';
import { parentPort } from 'worker_threads';

parentPort.on('message', (markdownString) => {
  parentPort.postMessage(marked.parse(markdownString));
});
js
// index.js

import { Worker } from 'worker_threads';
const markedWorker = new Worker('./markedWorker.js');

const markedTimeout = setTimeout(() => {
  markedWorker.terminate();
  throw new Error('Marked took too long!');
}, timeoutLimit);

markedWorker.on('message', (html) => {
  clearTimeout(markedTimeout);
  console.log(html);
  markedWorker.terminate();
});

markedWorker.postMessage(markdownString);

Web Worker

NOTE: Web Workers send the payload from postMessage in an object with the payload in a .data property

js
// markedWorker.js

importScripts('path/to/marked.umd.js');

onmessage = (e) => {
  const markdownString = e.data
  postMessage(marked.parse(markdownString));
};
js
// script.js

const markedWorker = new Worker('./markedWorker.js');

const markedTimeout = setTimeout(() => {
  markedWorker.terminate();
  throw new Error('Marked took too long!');
}, timeoutLimit);

markedWorker.onmessage = (e) => {
  clearTimeout(markedTimeout);
  const html = e.data;
  console.log(html);
  markedWorker.terminate();
};

markedWorker.postMessage(markdownString);
<h2 id="cli-extensions">CLI Extensions</h2>

You can use extensions in the CLI by creating a new CLI that imports marked and the marked binary.

js
// file: myMarked
#!/usr/bin/node

import { marked } from 'marked';
import customHeadingId from 'marked-custom-heading-id';

marked.use(customHeadingId());

import 'marked/bin/marked';
sh
$ ./myMarked -s "# heading {#custom-id}"
<h1 id="custom-id">heading</h1>