Introduction
Prism.js is a client-side syntax highlighting library designed to be small, fast, and extensible. It powers code blocks on MDN, Smashing Magazine, Drupal, and many static-site generators, rendering highlighted code without server-side processing.
What Prism.js Does
- Highlights code blocks in 300+ programming languages
- Runs in the browser with no build step required
- Extends via plugins for line numbers, copy buttons, diff highlighting, and more
- Supports custom themes through CSS variables
- Works with any HTML page, CMS, or static site generator
Architecture Overview
Prism.js tokenizes source code using language-specific grammars defined as regular expression objects. Each grammar maps token types (keyword, string, comment) to regex patterns. The tokenizer produces a flat token array, and the renderer wraps each token in a span with a CSS class. Plugins hook into the highlighting lifecycle via events like before-highlight and after-highlight.
Self-Hosting & Configuration
- Install via npm:
npm install prismjsor load from a CDN - Include only the languages you need to minimize bundle size
- Add plugins by importing their JS and CSS files
- Use the Prism.js download page to build a custom bundle with selected languages and plugins
- Server-side rendering is possible via Node.js with
Prism.highlight(code, grammar, language)
Key Features
- Core library is under 2 KB minified and gzipped
- Language definitions are lazy-loadable to keep initial payload small
- Works without a build step for quick integration into any HTML page
- Plugin ecosystem covers line numbers, autolinker, toolbar, and diff highlighting
- Themes are pure CSS, making customization straightforward
Comparison with Similar Tools
- Highlight.js — Automatic language detection but larger bundle; Prism requires explicit language classes
- Shiki — Uses VS Code TextMate grammars for exact VS Code colors; heavier but more accurate
- CodeMirror — Full code editor, not just a highlighter; much larger footprint
- Torchlight — Server-side highlighting API; requires external service
FAQ
Q: Does Prism.js auto-detect the language?
A: No. You specify the language via the class="language-xxx" attribute. The Autoloader plugin can load grammars on demand.
Q: Can I use Prism.js with React or Vue? A: Yes. Libraries like react-syntax-highlighter wrap Prism.js for use as a component.
Q: How do I add a new language?
A: Define a grammar object mapping token types to regex patterns and register it with Prism.languages.mylang = grammar.
Q: Is Prism.js still maintained? A: The project receives community contributions. For newer projects, also consider Shiki if VS Code parity matters.