Code Blocks
Code blocks are a simple way to display formatted code with syntax highlighting.
Code blocks by default are a simple way to display code. But, BlockNote also supports more advanced features like:
- Syntax highlighting
- Custom themes
- Multiple languages
- Tab indentation
These features are disabled by default to keep the default code block experience easy to use and reduce bundle size.
You can enable more advanced features by passing the codeBlock
option when creating the editor.
const editor = new BlockNoteEditor({
codeBlock: {
indentLineWithTab: true,
defaultLanguage: "typescript",
supportedLanguages: {
typescript: {
name: "TypeScript",
aliases: ["ts"],
},
},
createHighlighter: () =>
createHighlighter({
themes: ["light-plus", "dark-plus"],
langs: [],
}),
},
});
You can choose to enable only certain features, or none at all. Giving you the flexibility to use code blocks how you need in your app.
Block Shape
This describes the shape of a code block in BlockNote.
type CodeBlock = {
id: string;
type: "codeBlock";
props: {
language: string;
} & DefaultProps;
content: InlineContent[];
children: Block[];
};
Options
Basic Setup
To enable code block syntax highlighting, you can use the codeBlock
option in the useCreateBlockNote
hook.
First, install the package:
npm install @blocknote/code-block
Then use it like this:
import { codeBlock } from "@blocknote/code-block";
export default function App() {
const editor = useCreateBlockNote({
codeBlock,
});
return <BlockNoteView editor={editor} />;
}
Custom Themes & Languages
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.ts
This 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() {
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.