or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/marked@17.0.x
tile.json

tessl/npm-marked

tessl install tessl/npm-marked@17.0.0

A markdown parser built for speed

index.mddocs/

Marked

Marked is a high-performance, low-level markdown compiler that parses markdown without caching or blocking operations. It supports CommonMark and GitHub Flavored Markdown with zero runtime dependencies.

Quick Start

import { marked } from "marked";

const html = marked.parse('# Hello **World**');
// Output: <h1>Hello <strong>World</strong></h1>

Security: Marked does not sanitize HTML. Always use DOMPurify on output.

→ Complete Quick Start Guide

Package Information

  • Package: marked (npm)
  • Language: JavaScript/TypeScript
  • Installation: npm install marked
  • Node.js: >= 20
  • Bundle Size: ~20KB minified
  • Dependencies: Zero

Core API

FunctionPurposeReturns
marked.parse(src, options?)Parse markdown to HTMLstring | Promise<string>
marked.parseInline(src, options?)Parse inline markdown onlystring | Promise<string>
marked.setOptions(options)Set global optionstypeof marked
marked.use(...extensions)Add extensionstypeof marked
marked.lexer(src, options?)Tokenize markdownTokensList
marked.parser(tokens, options?)Parse tokens to HTMLstring

→ Complete API Reference

Core Imports

// Main import
import { marked } from "marked";

// Specific imports
import {
  marked,           // Main parse function
  parse,            // Alias for marked
  parseInline,      // Parse inline markdown only
  Lexer,            // Tokenizer class
  Parser,           // Parser class
  Renderer,         // HTML renderer class
  Tokenizer,        // Low-level tokenizer class
  Hooks,            // Processing hooks class
  Marked            // Instance class for isolated configs
} from "marked";

// CommonJS
const { marked } = require("marked");

→ Import Examples

Architecture

Marked uses a two-phase architecture:

  1. Lexing Phase: Lexer tokenizes markdown into a structured token tree
  2. Parsing Phase: Parser walks tokens and uses Renderer to generate HTML

Processing Pipeline:

Markdown → [Preprocess Hook] → Lexer → [ProcessAllTokens Hook] → 
[WalkTokens] → Parser + Renderer → [Postprocess Hook] → HTML

Benefits:

  • Token manipulation between phases
  • Custom renderers for different output formats
  • Multi-pass processing
  • Extension system at both phases

→ Architecture Details

Key Features

Markdown Support

  • ✅ CommonMark specification
  • ✅ GitHub Flavored Markdown (GFM)
    • Tables, strikethrough, task lists, autolinks
  • ✅ Full Unicode support
  • ✅ Pedantic mode (markdown.pl compatibility)

Performance

  • ⚡ Non-blocking parsing
  • ⚡ No caching overhead
  • ⚡ Optimized for large documents (<10ms for 100KB)
  • ⚡ Zero dependencies

Extensibility

  • 🔧 Custom tokenizers for new syntax
  • 🔧 Custom renderers for different output formats
  • 🔧 Hooks for pipeline interception
  • 🔧 Token walking for global modifications

→ Extension System

Common Use Cases

Use CaseGuideExample
Basic markdown parsingQuick StartBasic Usage
Custom syntaxExtensions GuideCustom Tokens
Syntax highlightingRendering GuideCode Highlighting
Custom HTML outputRendering GuideCustom Renderer
Front matter supportExtensions GuideFront Matter
Table of contentsToken WalkingTOC Generation

Configuration

// Set global options
marked.setOptions({
  gfm: true,        // Enable GitHub Flavored Markdown
  breaks: true,     // Convert \n to <br>
  pedantic: false,  // Don't fix markdown bugs
  silent: false     // Throw on errors
});

// Per-parse options
const html = marked.parse(markdown, { breaks: false });

// Isolated instances
const gfmMarked = new Marked({ gfm: true, breaks: true });

→ Configuration Options

Extension System

Marked supports four types of extensions:

  1. Tokenizer Extensions: Add new markdown syntax
  2. Renderer Extensions: Customize HTML output
  3. Hooks: Intercept processing pipeline
  4. walkTokens: Process all tokens globally
// Add custom emoji syntax
marked.use({
  extensions: [{
    name: 'emoji',
    level: 'inline',
    start(src) { return src.indexOf(':'); },
    tokenizer(src) {
      const match = src.match(/^:([a-z_]+):/);
      if (match) {
        return { type: 'emoji', raw: match[0], name: match[1] };
      }
    },
    renderer(token) {
      return `<span class="emoji emoji-${token.name}"></span>`;
    }
  }]
});

→ Extension System Guide | → Extension Reference

Security

Critical: Marked does NOT sanitize HTML output.

import { marked } from "marked";
import DOMPurify from "dompurify";

// UNSAFE
const unsafeHtml = marked.parse(userInput);

// SAFE
const dirty = marked.parse(userInput);
const clean = DOMPurify.sanitize(dirty);

Recommended sanitization libraries:

→ Security Best Practices

Error Handling

// Throw errors (default)
try {
  const html = marked.parse(markdown);
} catch (err) {
  console.error('Parse error:', err.message);
}

// Silent mode (return error as HTML)
marked.setOptions({ silent: true });
const html = marked.parse(markdown);

→ Error Handling Guide

Async Support

// Enable async mode
marked.setOptions({ async: true });

// Use async extensions
marked.use({
  async: true,
  async walkTokens(token) {
    if (token.type === 'link') {
      await validateUrl(token.href);
    }
  }
});

// Must await result
const html = await marked.parse(markdown, { async: true });

→ Async Patterns

CLI Usage

# Install globally
npm install -g marked

# Parse file
marked input.md -o output.html

# Parse with options
marked input.md --gfm --breaks

# From stdin
echo "# Hello" | marked

→ CLI Reference

Documentation Structure

Guides (Step-by-Step)

Examples (Real-World Usage)

Reference (Detailed Specifications)

Migration

From Other Libraries

From markdown-it:

// markdown-it
const md = require('markdown-it')();
const html = md.render(markdown);

// marked
import { marked } from "marked";
const html = marked.parse(markdown);

From showdown:

// showdown
const converter = new showdown.Converter();
const html = converter.makeHtml(markdown);

// marked
import { marked } from "marked";
const html = marked.parse(markdown);

→ Migration Guide

Performance

  • Non-blocking: No I/O operations
  • No caching: Each parse is independent
  • Memory efficient: Tokens kept in memory during parsing only
  • Fast: <10ms for 100KB documents (typical)
// Cache results for repeated content
const cache = new Map();

function cachedParse(markdown) {
  if (cache.has(markdown)) {
    return cache.get(markdown);
  }
  const html = marked.parse(markdown);
  cache.set(markdown, html);
  return html;
}

→ Performance Guide

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import { marked, MarkedOptions, Token, Tokens } from "marked";

// Type-safe configuration
const options: MarkedOptions = {
  gfm: true,
  breaks: true
};

// Type guards for token handling
function processToken(token: Token): void {
  if (token.type === 'heading') {
    // TypeScript knows this is Tokens.Heading
    console.log(`Level ${token.depth}: ${token.text}`);
  }
}

→ TypeScript Guide

Resources

Notes

  • No HTML Sanitization: Use DOMPurify or similar on output
  • GFM Enabled by Default: Tables, strikethrough, task lists, autolinks
  • Zero Dependencies: No runtime dependencies
  • Browser Support: All modern browsers (Baseline Widely Available)
  • Node.js: Requires Node.js >= 20
  • Unicode: Full Unicode support in pattern matching
  • Compliance: Supports CommonMark and GFM specifications