HighlightJS in TypeScript (and ES6)
This is a port of the highlight.js to a TypeScript (as well as ECMAScript 6).
NOTE: Currently not all languages are supported. PRs are welcome.
Usage example
import {
Options,
Highlighter,
registerLanguages,
htmlRender,
init,
process,
CPlusPlus,
TypeScript,
JavaScript,
Python,
Lua,
Markdown
} from 'highlight-ts';
registerLanguages(
CPlusPlus,
TypeScript,
JavaScript,
Python,
Lua,
Markdown
);
const options: Options = {
classPrefix: '',
};
const highlighter: Highlighter<string>
= init(htmlRender, options);
const source = `
interface Point {
x: number,
y: number,
}
function distance(a: Point, b: Point): number {
return Math.sqrt(
(a.x - b.x) ** 2 +
(a.y - b.y) ** 2);
}
`;
const language = 'ts';
const html = process(highlighter, source, language);
const languages = ['ts', 'js', 'md'];
const html = process(highlighter, source, languages);
const html = process(highlighter, source);
elm.innerHTML = `<pre>${html}</pre>`;
Differences from original
- Complete re-implementation using modern JavaScript syntax and features.
- No module-global state and configuration excluding the language modes registry.
- ES6 Module Syntax to compatibility with modern bundlers like Rollup which support Tree-Shaking.
- Support renderer API to render to HTML text as well as to a DOM-nodes directly or by VirtualDOM engines.
- Compiled mode it is another object not same as a source what get a little bit lower memory usage.
- Replaced some utility functions by ES6 syntax extensions which is provided by tslib for ES5 target.
- Fixed some modes to get more correct or advanced highlight.
Renderer API
Currently the renderer API is quite simple:
export interface Renderer<Output> {
text(chunk: string): Output;
wrap(className: string, chunk: Output): Output;
join(chunks: Output[]): Output;
}
- The
text()
call is using to render textual piece of source code. - The
wrap()
call is using to wrap rendered chunk into span with specified class. - The
join()
call is using to join several rendered chunks into single chunk.
By example we can implement HTML renderer like this:
import { Renderer } from 'highligh-ts';
const htmlRender: Renderer<string> = {
text: (chunk: string) => chunk
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>'),
join: (chunks: string[]) => chunks.join(''),
wrap: (className: string, chunk: string) =>
`<span class="${className}">${chunk}</span>`
};
HighlightJS API
See the types.ts source to understand highlight mode definition syntax.
Read the original highlightjs docs to get more help how to implement syntax highlighting modes.