Code Blocks and Containers
Rspress provides powerful code block features and custom containers for creating rich, informative documentation. This chapter explores how to use these features effectively.
Code Blocks
Basic Syntax Highlighting
Use language identifiers to enable syntax highlighting:
```javascript
function hello() {
console.log('Hello, World!');
}
```
```python
def hello():
print("Hello, World!")
```
```typescript
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
```Renders as:
function hello() {
console.log('Hello, World!');
}Supported Languages
Rspress supports a wide range of programming languages:
javascript, typescript, jsx, tsx, python, java, c, cpp, csharp,
go, rust, php, ruby, swift, kotlin, dart, sql, bash, shell,
html, css, scss, sass, less, json, yaml, xml, markdown, diffLine Numbers
Enabling Line Numbers
Line numbers are enabled by default. Control with showLineNumbers option:
```javascript showLineNumbers
function calculateSum(a, b) {
return a + b;
}
const result = calculateSum(5, 10);
console.log(result);
```Custom Starting Line Number
Start from a specific line number:
```javascript showLineNumbers=10
function processData(data) {
// This will start at line 10
return data.map(item => item * 2);
}
```Disabling Line Numbers
For simple snippets:
```bash {showLineNumbers=false}
npm install rspress
```Highlighting Lines
Single Line Highlight
Highlight specific lines to draw attention:
```javascript {2}
function greet(name) {
console.log(`Hello, ${name}!`); // This line is highlighted
return name;
}
```Multiple Line Highlight
Highlight multiple individual lines:
```javascript {1,3,5}
import React from 'react';
function Component() {
const [count, setCount] = useState(0);
return <div>{count}</div>;
}
```Line Range Highlight
Highlight ranges of lines:
```javascript {4-7}
function processArray(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(arr[i] * 2);
}
return result;
}
```Combined Highlights
Combine single lines and ranges:
```javascript {1,3-5,8}
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
return <div>{user?.name}</div>;
}
```Code Titles
Adding Filename
Display the filename for your code block:
```typescript title="config.ts"
export interface Config {
title: string;
description: string;
}
```Title with Path
Include the full file path:
```javascript title="src/components/Button/Button.tsx"
import React from 'react';
export function Button({ children, onClick }) {
return <button onClick={onClick}>{children}</button>;
}
```Diff Highlighting
Adding and Removing Lines
Show code changes:
```javascript
function greet(name) {
- console.log('Hello ' + name);
+ console.log(`Hello, ${name}!`);
}
```Complex Diffs
Show multiple changes:
```typescript
interface User {
name: string;
- age: number;
+ birthDate: Date;
email: string;
+ isActive: boolean;
}
function formatUser(user: User) {
- return `${user.name} (${user.age})`;
+ const age = calculateAge(user.birthDate);
+ return `${user.name} (${age})${user.isActive ? ' ✓' : ''}`;
}
```Code Groups
Creating Tabs
Organize related code in tabs:
:::code-group
```bash [npm]
npm install rspress
```
```bash [yarn]
yarn add rspress
```
```bash [pnpm]
pnpm add rspress
```
:::Examples in Different Languages
Show multiple languages in tabs:
:::code-group
```javascript [JavaScript]
function hello() {
console.log('Hello!');
}
```
```typescript [TypeScript]
function hello(): void {
console.log('Hello!');
}
```
```python [Python]
def hello():
print("Hello!")
```
:::Configuration Examples
Show different configuration options:
:::code-group
```json [package.json]
{
"name": "my-app",
"scripts": {
"dev": "rspress dev"
}
}
```
```typescript [rspress.config.ts]
import { defineConfig } from 'rspress/config';
export default defineConfig({
title: 'My Docs'
});
```
```yaml [.github/workflows/deploy.yml]
name: Deploy
on:
push:
branches: [main]
```
:::Custom Containers
Tip Container
Provide helpful tips for users:
::: tip
This is a helpful tip to guide users toward better understanding.
:::
::: tip Custom Title
You can customize the title of the tip.
:::Renders as:
TIP
This is a helpful tip to guide users toward better understanding.
Info Container
Provide additional information:
::: info
This provides supplementary background information.
:::
::: info Version Note
This feature was added in version 1.2.0.
:::INFO
This provides supplementary background information.
Warning Container
Warn users about potential issues:
::: warning
Be careful with this feature as it may affect performance.
:::
::: warning Deprecation Notice
This API is deprecated and will be removed in the next major version.
:::WARNING
Be careful with this feature as it may affect performance.
Danger Container
Highlight critical warnings:
::: danger
Do not use this in production! It's for testing purposes only.
:::
::: danger Data Loss Risk
This operation will permanently delete all data and cannot be undone.
:::DANGER
Do not use this in production! It's for testing purposes only.
Details Container
Create collapsible details sections:
::: details Click to see details
This is hidden content that only shows when clicked.
You can include code, lists, and other Markdown here:
```javascript
function example() {
return 'hidden content';
}:::
## Advanced Code Block Features
### Focus Mode
Highlight specific lines and dim others:
````markdown
```javascript {2-3} focus
function processData(data) {
const filtered = data.filter(item => item.active);
const mapped = filtered.map(item => item.value);
return mapped;
}
### Diff with Line Numbers
Combine line numbers with diffs:
````markdown
```typescript showLineNumbers
interface Config {
name: string;
- port: number;
+ port: number | string;
host: string;
+ timeout?: number;
}
```Word Highlighting
Highlight specific words:
```javascript /console.log/ /error/
function handleError(error) {
console.log('An error occurred');
console.error(error);
}
```Practical Examples
API Documentation
Document API endpoints:
### Get User
Retrieve details for a specific user.
**Endpoint:**
```
GET /api/users/:id
```
**Request:**
```bash title="cURL"
curl https://api.example.com/users/123 \
-H "Authorization: Bearer YOUR_TOKEN"
```
**Response:**
```json title="200 OK" {2-3}
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"createdAt": "2024-01-26T10:00:00Z"
}
```
**Error Response:**
```json title="404 Not Found"
{
"error": "User not found",
"code": "USER_NOT_FOUND"
}
```Tutorial Steps
Step-by-step guidance:
## Step 1: Installation
:::code-group
```bash [npm]
npm install rspress
```
```bash [yarn]
yarn add rspress
```
:::
## Step 2: Initialize
```bash
npx rspress init my-docs
cd my-docs
```
## Step 3: Configure
```typescript title="rspress.config.ts" {4-6}
import { defineConfig } from 'rspress/config';
export default defineConfig({
title: 'My Documentation',
description: 'A comprehensive guide',
themeConfig: {
sidebar: {
'/guide/': [/* ... */]
}
}
});
```
::: tip
Customize the configuration to match your needs.
:::Migration Guide
Show code changes:
## Migrating from v1 to v2
### Configuration Changes
Old configuration format:
```javascript title="rspress.config.js (v1)"
module.exports = {
title: 'My Site',
theme: {
navbar: [/* ... */]
}
};
```
New configuration format:
```typescript title="rspress.config.ts (v2)"
import { defineConfig } from 'rspress/config';
export default defineConfig({
title: 'My Site',
themeConfig: {
navbar: [/* ... */]
}
});
```
### API Changes
```typescript
// Old way (v1)
- import { createPage } from 'rspress';
+ import { definePage } from 'rspress/runtime';
- const page = createPage({ /* ... */ });
+ const page = definePage({ /* ... */ });
```
::: warning Breaking Change
The `createPage` API has been removed. Use `definePage` instead.
:::Configuration
Global Configuration
Customize code blocks in rspress.config.ts:
import { defineConfig } from 'rspress/config';
export default defineConfig({
markdown: {
// Configure code highlighting
highlight: {
theme: 'github-dark',
languages: ['javascript', 'typescript', 'bash']
},
// Line numbers configuration
showLineNumbers: true,
// Default code copy button
codeCopy: true
}
});Theme Configuration
Customize code block theme:
export default defineConfig({
markdown: {
highlight: {
// Use different themes
theme: {
light: 'github-light',
dark: 'github-dark'
}
}
}
});Custom Languages
Add custom language support:
export default defineConfig({
markdown: {
highlight: {
languages: [
'javascript',
'typescript',
// Add custom language
{
id: 'myLang',
scopeName: 'source.myLang',
grammar: {/* ... */}
}
]
}
}
});Styling Customization
CSS Variables
Customize code blocks with CSS variables:
/* styles/custom.css */
:root {
--rp-code-bg: #1e1e1e;
--rp-code-color: #d4d4d4;
--rp-code-line-number-color: #858585;
--rp-code-highlight-bg: rgba(255, 255, 255, 0.1);
--rp-code-title-bg: #2d2d2d;
}Custom Classes
Add custom styles:
/* Custom code block styles */
.rspress-code-block {
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
/* Custom line highlighting */
.rspress-code-block .highlighted {
background: rgba(255, 255, 0, 0.1);
border-left: 3px solid #ffd700;
}
/* Custom container styles */
.rspress-container.tip {
border-left: 4px solid #42b983;
}
.rspress-container.warning {
border-left: 4px solid #ffa500;
}
.rspress-container.danger {
border-left: 4px solid #ff0000;
}Best Practices
Code Organization
- Use Meaningful Titles
✅ Good
```typescript title="src/utils/validation.ts"
export function validateEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
```
❌ Bad
```typescript title="file.ts"
function validate(s) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
}
```- Highlight Important Lines
✅ Emphasize key parts
```javascript {5-7}
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
// This is important error handling
if (!response.ok) {
throw new Error(data.message);
}
return data;
} catch (error) {
console.error(error);
}
}
```- Use Code Groups for Alternatives
✅ Clear alternatives
:::code-group
```bash [npm]
npm install package
```
```bash [yarn]
yarn add package
```
:::
❌ Separate blocks
```bash
npm install package
```
or
```bash
yarn add package
```Container Usage
- Choose the Right Container Type
✅ Appropriate usage
::: tip
Use the keyboard shortcut Ctrl+K to search quickly.
:::
::: warning
This feature is not available on mobile devices.
:::
::: danger
Deleting this resource will permanently remove all associated data.
:::- Provide Clear Titles
✅ Descriptive title
::: warning Performance Impact
Using this method on large datasets may impact performance.
:::
❌ Generic title
::: warning
Be careful with this.
:::- Combine Content Types
::: tip Best Practice
Always validate user input:
```typescript
function validateInput(input: string): boolean {
return input.length > 0 && input.length < 100;
}See the Validation Guide for more details. :::
## Troubleshooting
### Common Issues
1. **Syntax Highlighting Not Working**
```markdown
Issue: Code is not highlighted
Solution: Check language identifier spelling
❌ Wrong
```javascrip
// Typo✅ Correct
// Correct language identifier
2. **Line Highlights Not Showing**
````markdown
Issue: Highlighted lines not applied
Solution: Ensure correct syntax
❌ Wrong
```javascript {1, 2, 3}
// Spaces in highlight range✅ Correct
// No spaces
3. **Container Not Rendering**
```markdown
Issue: Container appears as plain text
Solution: Check syntax and colons
❌ Wrong
:: tip
Missing colon
::
✅ Correct
::: tip
Three colons
:::
```
### Debug Tips
1. **Check Configuration**
```typescript
// Enable debug in rspress.config.ts
export default defineConfig({
markdown: {
debug: true, // Enable debug logging
}
});
```
2. **Verify Language Support**
```javascript
// Check available languages
import { getHighlighter } from 'rspress/runtime';
const highlighter = await getHighlighter();
console.log(highlighter.getLoadedLanguages());
```
3. **Test Containers**
```markdown
<!-- Test each container type -->
::: tip
Test tip
:::
::: info
Test info
:::
::: warning
Test warning
:::
::: danger
Test danger
:::
```
---
## Next Steps
- Learn about [Custom Pages](./custom-pages.md)
- Explore [Custom Theme](./custom-theme.md)
- Read about [Built-in Components](./built-in-components.md)
---
::: tip Best Practices
- Use appropriate language identifiers for all code blocks
- Highlight important lines to draw attention
- Provide meaningful titles for files
- Use code groups for related alternatives
- Choose appropriate container types
:::
::: warning Performance
- Avoid excessive code blocks on a single page
- Consider code folding for long snippets
- Optimize custom syntax highlighters
:::
::: info Resources
- [Shiki Themes](https://github.com/shikijs/shiki/blob/main/docs/themes.md)
- [Language Support](https://github.com/shikijs/shiki/blob/main/docs/languages.md)
- [Rspress Markdown Guide](https://rspress.dev/guide/basic/markdown)
:::