| title | Code Block Syntax Highlighting |
|---|---|
| description | This section explains how to add syntax highlighting to code blocks. |
| imageTitle | Code Block Syntax Highlighting |
import { Example } from "@/components/example";
To enable code block syntax highlighting, you can use the codeBlock option in the useCreateBlockNote hook. This is excluded by default to reduce bundle size.
We've created a default setup which automatically includes some of the most common languages in the most optimized way possible. The language syntaxes are loaded on-demand to ensure the smallest bundle size for your users.
To use it, you can do the following:
npm install @blocknote/code-blockAnd then you can use it like this:
import { codeBlock } from "@blocknote/code-block";
export default function App() {
// Creates a new editor instance.
const editor = useCreateBlockNote({
codeBlock,
});
// Renders the editor instance using a React component.
return <BlockNoteView editor={editor} />;
}See the code block example for a more detailed example.
To configure a code block highlighting theme and language, you can use the codeBlock option in the useCreateBlockNote hook.
This allows you to configure a shiki highlighter for the code blocks of your editor, allowing you to tailor the themes and languages you would like to use.
To create a syntax highlighter, you can use the shiki-codegen CLI for generating the code to create a syntax highlighter for your languages and themes.
For example to create a syntax highlighter using the optimized javascript engine, javascript, typescript, vue, with light and dark themes, you can run the following command:
npx shiki-codegen --langs javascript,typescript,vue --themes light,dark --engine javascript --precompiled ./shiki.bundle.tsThis will generate a shiki.bundle.ts file that you can use to create a syntax highlighter for your editor.
Like this:
import { createHighlighter } from "./shiki.bundle.js";
export default function App() {
// Creates a new editor instance.
const editor = useCreateBlockNote({
codeBlock: {
indentLineWithTab: true,
defaultLanguage: "typescript",
supportedLanguages: {
typescript: {
name: "TypeScript",
aliases: ["ts"],
},
},
createHighlighter: () =>
createHighlighter({
themes: ["light-plus", "dark-plus"],
langs: [],
}),
},
});
return <BlockNoteView editor={editor} />;
}See the custom code block example for a more detailed example.