Code Blocks
Overview
Code blocks are an essential part of technical documentation. VitePress enhances Markdown code blocks with features like syntax highlighting, line highlighting, line numbers, and interactive code examples. This guide covers all the code block features available in VitePress and how to use them effectively.
Basic Syntax
Create a code block using triple backticks with an optional language identifier:
```js
// This is a JavaScript code block
function greet(name) {
return `Hello, ${name}!`;
}
## Syntax Highlighting
VitePress uses [Shiki](https://shiki.matsu.io/) for syntax highlighting, which provides accurate highlighting based on TextMate grammars.
### Supported Languages
VitePress supports a wide range of programming languages, including:
- JavaScript/TypeScript (`js`, `ts`)
- HTML/XML (`html`, `xml`)
- CSS/SCSS/LESS (`css`, `scss`, `less`)
- Python (`python`, `py`)
- Ruby (`ruby`)
- Java (`java`)
- C/C++ (`c`, `cpp`)
- Go (`go`)
- Rust (`rust`)
- PHP (`php`)
- Shell/Bash (`sh`, `bash`)
- SQL (`sql`)
- YAML (`yaml`)
- JSON (`json`)
- Markdown (`md`, `markdown`)
- And many more...
### Custom Theme
You can customize the syntax highlighting theme in your VitePress configuration:
```js
// .vitepress/config.js
export default {
markdown: {
theme: 'github-dark', // Default theme for dark mode
lightTheme: 'github-light' // Theme for light mode
}
}
Available themes include:
'github-dark'
'github-light'
'vitesse-dark'
'vitesse-light'
- And many more
Line Highlighting
Highlight specific lines by adding line numbers in curly braces:
```js{2,4-6}
function hello() {
// This line is highlighted
console.log('Hello World');
// These lines are
// also
// highlighted
}
## Line Numbers
Add line numbers to your code blocks:
```md
```js:line-numbers
function hello() {
console.log('Hello World');
}
You can combine line numbers with highlighting:
```md
```js:line-numbers{2}
function hello() {
console.log('Hello World'); // This line is highlighted
}
## Focus Highlighting
Focus on specific lines while dimming others:
```md
```js:focus{2}
function hello() {
console.log('Hello World'); // This line is in focus
}
## Diff Highlighting
Show code differences with `+` and `-` prefixes:
```md
```diff
- function oldVersion() {
- return 'old';
+ function newVersion() {
+ return 'new';
}
## Code Groups
Group related code blocks together with tabs:
```md
::: code-group
```js [config.js]
export default {
theme: 'default'
}
import { defineConfig } from 'vitepress'
export default defineConfig({
theme: 'default'
})
:::
## Importing Code Snippets
Import code from external files:
```md
<<< @/filepath/example.js
You can also specify line ranges:
<<< @/filepath/example.js{2-5}
And add language and highlighting:
<<< @/filepath/example.js{2-5} [js:line-numbers]
Interactive Code Examples
Create interactive code examples using Vue components:
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
# Interactive Counter
Current count: {{ count }}
<button @click="count++">Increment</button>
```js
// The code for the counter
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
## Advanced Features
### Custom Containers
Combine code blocks with custom containers:
```md
::: info Using the API
```js
import { api } from 'mylib'
api.method()
The API method accepts these parameters... :::
### Code Block Titles
Add titles to your code blocks:
```md
```js:title=src/utils.js
export function helper() {
return 'Helper function'
}
### Twoslash Integration
For TypeScript examples, you can use [Twoslash](https://github.com/microsoft/TypeScript-Website/tree/v2/packages/ts-twoslasher) annotations:
```md
```ts twoslash
// @errors: 2339
interface User {
firstName: string
lastName: string
}
function getFullName(user: User) {
return user.firstName + ' ' + user.lastName
}
// Will show an error for accessing 'title'
const name = getFullName({ firstName: 'John', lastName: 'Doe', title: 'Mr' })
## Customizing Code Blocks
### Custom CSS
Style your code blocks with custom CSS:
```css
/* .vitepress/theme/custom.css */
:root {
--vp-code-block-bg: rgba(125, 125, 125, 0.04);
}
.dark {
--vp-code-block-bg: rgba(0, 0, 0, 0.2);
}
div[class*='language-'] {
border-radius: 8px;
}
Custom Code Block Components
Create custom code block components:
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import CustomCodeBlock from './components/CustomCodeBlock.vue'
import './custom.css'
export default {
...DefaultTheme,
enhanceApp({ app }) {
app.component('CustomCodeBlock', CustomCodeBlock)
}
}
Best Practices
Choose the Right Language: Always specify the language for proper syntax highlighting.
Keep Examples Concise: Focus on the relevant code, omitting unnecessary details.
Use Line Highlighting: Highlight important lines to draw attention to key concepts.
Provide Context: Add comments or explanations around code blocks.
Group Related Examples: Use code groups for alternative implementations or different languages.
Test Your Code: Ensure that code examples actually work.
Consider Accessibility: Ensure code blocks are accessible to screen readers.
Frequently Asked Questions
How can I add a copy button to code blocks?
VitePress includes copy buttons by default. If you want to customize it:
// .vitepress/config.js
export default {
markdown: {
// Configure copy code options
copyCode: {
buttonText: 'Copy',
successText: 'Copied!'
}
}
}
Can I disable syntax highlighting for specific blocks?
Yes, use text
as the language identifier:
```text
This will be displayed without syntax highlighting
### How do I display triple backticks in my code?
You can use four backticks to wrap a code block that contains triple backticks:
````md
function example() {
return true
}
Related Resources
This document will be continuously updated. If you have any questions, please provide feedback through GitHub Issues.