md2html-themes
v1.1.1
Published
A lightweight, dependency-minimal JavaScript library for converting Markdown to themed HTML in-browser
Downloads
20
Maintainers
Readme
md2html
A lightweight, dependency-minimal JavaScript library for converting Markdown to themed HTML directly in the browser.
Features
- GitHub Flavored Markdown - Full GFM support including tables, task lists, and strikethrough
- Three Built-in Themes - Light, dark, and fully customizable themes
- XSS Protection - Built-in HTML sanitization with DOMPurify
- Zero Server Required - Runs entirely in the browser
- Lightweight - Minimal dependencies, optimized bundle size
- Accessible - WCAG-compliant UI with keyboard navigation
- Responsive - Mobile-friendly interface
- Fast - Instant live preview with theme switching
Quick Start
Installation
NPM (Recommended):
npm install md2html-themesYarn:
yarn add md2html-themesCDN:
<script src="https://unpkg.com/md2html-themes@latest/dist/md2html.min.js"></script>📦 NPM Package: md2html-themes
Getting Started Example
After installing via NPM, create a simple HTML file and JavaScript module:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>md2html Example</title>
</head>
<body>
<h1>Markdown to HTML Converter</h1>
<textarea id="input" rows="10" cols="80">
# Hello World
This is **bold** and this is *italic*.
- Item 1
- Item 2
- Item 3
</textarea>
<button id="convert">Convert</button>
<div id="output"></div>
<script type="module" src="./app.js"></script>
</body>
</html>app.js:
import md2html from 'md2html-themes';
document.getElementById('convert').addEventListener('click', async () => {
const markdown = document.getElementById('input').value;
const result = await md2html.parse(markdown);
document.getElementById('output').innerHTML = result.html;
md2html.applyTheme(md2html.themes.light);
});Then serve with a local dev server:
# Option 1: Using Vite (recommended)
npx vite
# Option 2: Using http-server
npx http-server
# Option 3: Using Python
python -m http.server 8000Open the URL shown in the terminal (usually http://localhost:5173 for Vite).
Note: You cannot open the HTML file directly (
file://) due to CORS restrictions. You must use a local server.
Basic Usage (NPM)
import md2html from 'md2html-themes';
// Parse markdown
const result = await md2html.parse('# Hello World\n\nThis is **bold** text.');
// Display in your web page
document.getElementById('preview').innerHTML = result.html;
// Apply a theme with automatic CSS injection (NEW in v1.1.0!)
md2html.applyThemeWithStyles(md2html.themes.dark, document.getElementById('preview'));
// Or use legacy method (requires manual CSS)
md2html.applyTheme(md2html.themes.dark);
// Or generate a complete HTML document
const fullHtml = md2html.toFullHtml(
result.html,
md2html.themes.dark,
{ title: 'My Document' }
);Browser Usage (CDN - No Build Step)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>md2html Demo</title>
</head>
<body>
<div id="preview"></div>
<!-- Load from CDN -->
<script src="https://unpkg.com/md2html-themes@latest/dist/md2html.min.js"></script>
<script>
// md2html is now available as a global variable
(async () => {
const result = await md2html.parse('# Hello from CDN!\n\n**No build step required!**');
const preview = document.getElementById('preview');
preview.innerHTML = result.html;
// NEW in v1.1.0: Automatic CSS injection - no manual CSS needed!
md2html.applyThemeWithStyles(md2html.themes.light, preview);
})();
</script>
</body>
</html>Documentation
Comprehensive documentation is available in the /docs directory:
- Installation Guide - 📦 NPM, CDN, and installation methods
- Usage Guide - 🚀 Detailed usage examples and code snippets
- API Reference - Complete API documentation
- Introduction - Overview and features
- Theme Schema - Theme customization guide
- Testing - Testing strategy and guidelines
- Extending to PDF - Future PDF export plans
- Manual Test Cases - QA checklist
Project Structure
md2html/
├── src/
│ ├── index.js # Public API
│ ├── parser.js # Markdown parsing
│ ├── sanitizer.js # XSS protection
│ ├── theme.js # Theme engine
│ ├── ui/
│ │ ├── demo.js # Demo application
│ │ └── components/ # UI components
│ └── styles/ # CSS themes
├── public/
│ └── index.html # Demo page
├── tests/
│ ├── unit/ # Unit tests
│ └── e2e/ # E2E tests
├── docs/ # Documentation
├── samples/ # Sample markdown files
└── dist/ # Built files
Development
Commands
# Start development server
npm run start
# Build for production
npm run build
# Run unit tests
npm test
# Run E2E tests
npm run test:e2e
# Run linter
npm run lintDependencies
Runtime:
- marked - Markdown parser (chosen for lightweight footprint and GFM support)
- DOMPurify - XSS sanitization
Development:
- Vite - Dev server and build tool
- Vitest - Unit testing
- Playwright - E2E testing
- Rollup - Library bundling
Why These Dependencies?
marked: Lightweight (~50KB), fast, well-maintained, excellent GFM support, and highly extensible.
DOMPurify: Industry standard for HTML sanitization, actively maintained, comprehensive XSS protection.
Supported Markdown Features
- Headings (H1-H4)
- Paragraphs and line breaks
- Bold, italic, ~~strikethrough~~
- Links and images
- Ordered and unordered lists
- Nested lists
- Task lists (- [ ] Todo)
- Tables with alignment
- Code blocks with language tags
- Inline
code - Blockquotes
- Horizontal rules
- Frontmatter (YAML)
Themes
Built-in Themes
- Light - Clean, professional light theme
- Dark - Eye-friendly dark theme
- Custom - Fully editable theme with live preview
Theme Application (Two Methods)
Method 1: Automatic CSS Injection (NEW in v1.1.0)
Recommended for most users - CSS styles are automatically injected:
// No manual CSS required! Everything is handled automatically.
md2html.applyThemeWithStyles(md2html.themes.dark, container);<!DOCTYPE html>
<html>
<body>
<div id="output"></div>
<script src="https://unpkg.com/md2html-themes@latest/dist/md2html.min.js"></script>
<script>
(async () => {
const result = await md2html.parse('# Hello World\n\nThis is **bold** text.');
const output = document.getElementById('output');
output.innerHTML = result.html;
// Magic! CSS styles are automatically included - no manual CSS needed!
md2html.applyThemeWithStyles(md2html.themes.light, output);
})();
</script>
</body>
</html>Method 2: Manual CSS Variables (Legacy)
For advanced users who want full control over styling:
// Sets CSS variables - you provide the CSS that uses them
md2html.applyTheme(md2html.themes.dark, container);<style>
.my-markdown {
color: var(--color-text);
background: var(--color-surface);
font-family: var(--font-family);
/* ... more CSS using the variables ... */
}
</style>Theme Customization
// Clone and customize
const myTheme = md2html.cloneTheme(md2html.themes.light);
myTheme.colors.background = '#fef3c7';
myTheme.colors.text = '#78350f';
myTheme.typography.baseFontSize = '18px';
// Apply with automatic CSS (recommended)
md2html.applyThemeWithStyles(myTheme, container);
// Or apply with manual CSS variables
md2html.applyTheme(myTheme);
// Export and import
const json = md2html.exportTheme(myTheme);
localStorage.setItem('myTheme', json);
const savedTheme = md2html.importTheme(json);
md2html.applyThemeWithStyles(savedTheme, container);See Theme Schema for complete customization options.
Security
md2html includes built-in XSS protection via DOMPurify. All HTML output is sanitized by default to prevent script injection and other attacks.
// Sanitization is enabled by default
const result = await md2html.parse(markdown);
// Check for dangerous content
if (md2html.hasDangerousContent(html)) {
console.warn('Content contains potentially dangerous HTML');
}See samples/sample-xss.md for tested attack vectors.
Browser Support
- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
- Mobile browsers (iOS Safari, Chrome Mobile)
Uses modern JavaScript features:
- ES Modules
- Async/await
- CSS Custom Properties
- Fetch API
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
Development Workflow
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Run tests (
npm test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Testing
# Run all tests
npm test
# Run with coverage
npm test -- --coverage
# Run E2E tests
npm run test:e2e
# Run in watch mode
npm test -- --watchSee Testing Documentation for details.
License
MIT © 2025
See LICENSE for details.
Roadmap
- [ ] PDF export (Puppeteer-based)
- [ ] Syntax highlighting for code blocks
- [ ] Math rendering (KaTeX)
- [ ] Mermaid diagram support
- [ ] Custom renderer hooks
- [ ] React/Vue wrapper components
- [ ] VS Code extension
- [ ] CLI tool
Acknowledgments
Support
Built with ❤️ using vanilla JavaScript
