slidev-monaco-editor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMonaco Editor in Slidev
Slidev中的Monaco Editor
This skill covers integrating Monaco Editor (the editor powering VS Code) into your Slidev presentations for live coding, interactive demos, and executable code blocks.
本技能介绍如何将Monaco Editor(驱动VS Code的编辑器)集成到你的Slidev演示文稿中,以实现实时编码、交互式演示和可执行代码块功能。
When to Use This Skill
适用场景
- Live coding demonstrations
- Interactive code editing during presentations
- Running code examples in real-time
- Teaching programming concepts
- Showing auto-completion and type hints
- 实时编码演示
- 演示过程中的交互式代码编辑
- 实时运行代码示例
- 教授编程概念
- 展示自动补全和类型提示
Enabling Monaco Editor
启用Monaco Editor
Basic Monaco Block
基础Monaco代码块
Add to any code block:
{monaco}markdown
```typescript {monaco}
const greeting = 'Hello, World!'
console.log(greeting)
```This creates an editable code block with:
- Syntax highlighting
- Auto-completion
- Type checking (for TypeScript)
- Bracket matching
在任意代码块中添加:
{monaco}markdown
```typescript {monaco}
const greeting = 'Hello, World!'
console.log(greeting)
```这将创建一个具备以下功能的可编辑代码块:
- 语法高亮
- 自动补全
- 类型检查(针对TypeScript)
- 括号匹配
Monaco with Line Highlighting
带行高亮的Monaco代码块
markdown
```typescript {monaco}{2,3}
const a = 1
const b = 2 // highlighted
const c = 3 // highlighted
```markdown
```typescript {monaco}{2,3}
const a = 1
const b = 2 // highlighted
const c = 3 // highlighted
```Monaco Runner
Monaco代码运行器
Execute code directly in the presentation:
可在演示文稿中直接执行代码:
JavaScript Runner
JavaScript运行器
markdown
```javascript {monaco-run}
const numbers = [1, 2, 3, 4, 5]
const doubled = numbers.map(n => n * 2)
console.log(doubled)
```Click "Run" to execute and see output.
markdown
```javascript {monaco-run}
const numbers = [1, 2, 3, 4, 5]
const doubled = numbers.map(n => n * 2)
console.log(doubled)
```点击“Run”按钮执行代码并查看输出。
TypeScript Runner
TypeScript运行器
markdown
```typescript {monaco-run}
interface User {
name: string
age: number
}
const user: User = {
name: 'John',
age: 30
}
console.log(`${user.name} is ${user.age} years old`)
```markdown
```typescript {monaco-run}
interface User {
name: string
age: number
}
const user: User = {
name: 'John',
age: 30
}
console.log(`${user.name} is ${user.age} years old`)
```Auto-Run on Load
加载时自动运行
markdown
```javascript {monaco-run} {autorun:true}
console.log('This runs automatically!')
```markdown
```javascript {monaco-run} {autorun:true}
console.log('This runs automatically!')
```Show Output Only
仅显示输出
markdown
```javascript {monaco-run} {showOutputAt:'+1'}
// Output shows after one click
console.log('Hello!')
```markdown
```javascript {monaco-run} {showOutputAt:'+1'}
// Output shows after one click
console.log('Hello!')
```Configuration Options
配置选项
Editor Height
编辑器高度
markdown
```typescript {monaco}{height:'300px'}
// Taller editor
function longFunction() {
// ...
}
```markdown
```typescript {monaco}{height:'300px'}
// Taller editor
function longFunction() {
// ...
}
```Read-Only Mode
只读模式
markdown
```typescript {monaco}{readonly:true}
// Cannot be edited
const CONSTANT = 'value'
```markdown
```typescript {monaco}{readonly:true}
// Cannot be edited
const CONSTANT = 'value'
```Diff Editor
差异编辑器
markdown
```typescript {monaco-diff}
const original = 'Hello'
~~~
const modified = 'Hello, World!'
```markdown
```typescript {monaco-diff}
const original = 'Hello'
~~~
const modified = 'Hello, World!'
```Monaco Setup Configuration
Monaco设置配置
setup/monaco.ts
setup/monaco.ts
typescript
import { defineMonacoSetup } from '@slidev/types'
export default defineMonacoSetup((monaco) => {
// Editor options
return {
editorOptions: {
fontSize: 14,
fontFamily: 'JetBrains Mono, monospace',
minimap: { enabled: false },
lineNumbers: 'on',
wordWrap: 'on',
tabSize: 2,
scrollBeyondLastLine: false,
automaticLayout: true,
},
// Light/dark theme
theme: {
light: 'vs',
dark: 'vs-dark',
},
}
})typescript
import { defineMonacoSetup } from '@slidev/types'
export default defineMonacoSetup((monaco) => {
// Editor options
return {
editorOptions: {
fontSize: 14,
fontFamily: 'JetBrains Mono, monospace',
minimap: { enabled: false },
lineNumbers: 'on',
wordWrap: 'on',
tabSize: 2,
scrollBeyondLastLine: false,
automaticLayout: true,
},
// Light/dark theme
theme: {
light: 'vs',
dark: 'vs-dark',
},
}
})Custom Themes
自定义主题
typescript
import { defineMonacoSetup } from '@slidev/types'
export default defineMonacoSetup((monaco) => {
// Define custom theme
monaco.editor.defineTheme('my-theme', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'comment', foreground: '6A9955' },
{ token: 'keyword', foreground: 'C586C0' },
],
colors: {
'editor.background': '#1a1a2e',
},
})
return {
theme: {
dark: 'my-theme',
light: 'vs',
},
}
})typescript
import { defineMonacoSetup } from '@slidev/types'
export default defineMonacoSetup((monaco) => {
// Define custom theme
monaco.editor.defineTheme('my-theme', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'comment', foreground: '6A9955' },
{ token: 'keyword', foreground: 'C586C0' },
],
colors: {
'editor.background': '#1a1a2e',
},
})
return {
theme: {
dark: 'my-theme',
light: 'vs',
},
}
})Type Definitions
类型定义
Adding Types for Libraries
添加库类型
typescript
// setup/monaco.ts
import { defineMonacoSetup } from '@slidev/types'
export default defineMonacoSetup(async (monaco) => {
// Add React types
const reactTypes = await fetch(
'https://unpkg.com/@types/react/index.d.ts'
).then(r => r.text())
monaco.languages.typescript.typescriptDefaults.addExtraLib(
reactTypes,
'file:///node_modules/@types/react/index.d.ts'
)
})typescript
// setup/monaco.ts
import { defineMonacoSetup } from '@slidev/types'
export default defineMonacoSetup(async (monaco) => {
// Add React types
const reactTypes = await fetch(
'https://unpkg.com/@types/react/index.d.ts'
).then(r => r.text())
monaco.languages.typescript.typescriptDefaults.addExtraLib(
reactTypes,
'file:///node_modules/@types/react/index.d.ts'
)
})Inline Type Definitions
内联类型定义
markdown
```typescript {monaco}
// Types defined inline
interface Todo {
id: number
text: string
completed: boolean
}
const todos: Todo[] = [
{ id: 1, text: 'Learn Slidev', completed: true },
{ id: 2, text: 'Create presentation', completed: false },
]
```markdown
```typescript {monaco}
// Types defined inline
interface Todo {
id: number
text: string
completed: boolean
}
const todos: Todo[] = [
{ id: 1, text: 'Learn Slidev', completed: true },
{ id: 2, text: 'Create presentation', completed: false },
]
```Interactive Examples
交互式示例
Counter Demo
计数器演示
markdown
```typescript {monaco-run}
// Interactive counter
let count = 0
function increment() {
count++
console.log(`Count: ${count}`)
}
// Click Run multiple times!
increment()
```markdown
```typescript {monaco-run}
// Interactive counter
let count = 0
function increment() {
count++
console.log(`Count: ${count}`)
}
// Click Run multiple times!
increment()
```API Simulation
API模拟
markdown
```typescript {monaco-run}
// Simulated API call
async function fetchUser(id: number) {
// Simulate network delay
await new Promise(r => setTimeout(r, 500))
return {
id,
name: 'John Doe',
email: 'john@example.com'
}
}
const user = await fetchUser(1)
console.log(user)
```markdown
```typescript {monaco-run}
// Simulated API call
async function fetchUser(id: number) {
// Simulate network delay
await new Promise(r => setTimeout(r, 500))
return {
id,
name: 'John Doe',
email: 'john@example.com'
}
}
const user = await fetchUser(1)
console.log(user)
```Algorithm Visualization
算法可视化
markdown
```typescript {monaco-run}
// Bubble sort with steps
function bubbleSort(arr: number[]) {
const result = [...arr]
const steps: string[] = []
for (let i = 0; i < result.length; i++) {
for (let j = 0; j < result.length - i - 1; j++) {
if (result[j] > result[j + 1]) {
[result[j], result[j + 1]] = [result[j + 1], result[j]]
steps.push(`Swap: [${result.join(', ')}]`)
}
}
}
return { result, steps }
}
const { result, steps } = bubbleSort([5, 3, 8, 4, 2])
console.log('Steps:', steps.length)
steps.forEach(s => console.log(s))
console.log('Final:', result)
```markdown
```typescript {monaco-run}
// Bubble sort with steps
function bubbleSort(arr: number[]) {
const result = [...arr]
const steps: string[] = []
for (let i = 0; i < result.length; i++) {
for (let j = 0; j < result.length - i - 1; j++) {
if (result[j] > result[j + 1]) {
[result[j], result[j + 1]] = [result[j + 1], result[j]]
steps.push(`Swap: [${result.join(', ')}]`)
}
}
}
return { result, steps }
}
const { result, steps } = bubbleSort([5, 3, 8, 4, 2])
console.log('Steps:', steps.length)
steps.forEach(s => console.log(s))
console.log('Final:', result)
```Code Runner Patterns
代码运行器使用模式
Show Concept Then Let Edit
先展示概念再允许编辑
markdown
undefinedmarkdown
undefinedArray Methods
数组方法
typescript
const numbers = [1, 2, 3, 4, 5]
// Try changing the function!
const result = numbers
.filter(n => n % 2 === 0)
.map(n => n * 2)
console.log(result)Try modifying the code to:
- Filter odd numbers
- Triple instead of double
undefinedtypescript
const numbers = [1, 2, 3, 4, 5]
// 尝试修改这个函数!
const result = numbers
.filter(n => n % 2 === 0)
.map(n => n * 2)
console.log(result)尝试修改代码实现:
- 筛选奇数
- 将数值改为三倍而非两倍
undefinedInteractive Quiz
交互式测验
markdown
undefinedmarkdown
undefinedFix the Bug
修复代码漏洞
typescript
// This code has a bug - can you fix it?
function reverseString(str: string) {
return str.split('').reserve().join('')
}
console.log(reverseString('hello'))
// Expected: 'olleh'undefinedtypescript
// 这段代码有漏洞 - 你能修复它吗?
function reverseString(str: string) {
return str.split('').reserve().join('')
}
console.log(reverseString('hello'))
// 预期输出: 'olleh'undefinedLive Data Manipulation
实时数据处理
markdown
```typescript {monaco-run}
const data = [
{ name: 'Alice', score: 85 },
{ name: 'Bob', score: 92 },
{ name: 'Charlie', score: 78 },
]
// Calculate statistics
const average = data.reduce((sum, d) => sum + d.score, 0) / data.length
const highest = Math.max(...data.map(d => d.score))
const passing = data.filter(d => d.score >= 80)
console.log(`Average: ${average.toFixed(1)}`)
console.log(`Highest: ${highest}`)
console.log(`Passing: ${passing.map(d => d.name).join(', ')}`)
```markdown
```typescript {monaco-run}
const data = [
{ name: 'Alice', score: 85 },
{ name: 'Bob', score: 92 },
{ name: 'Charlie', score: 78 },
]
// 计算统计数据
const average = data.reduce((sum, d) => sum + d.score, 0) / data.length
const highest = Math.max(...data.map(d => d.score))
const passing = data.filter(d => d.score >= 80)
console.log(`Average: ${average.toFixed(1)}`)
console.log(`Highest: ${highest}`)
console.log(`Passing: ${passing.map(d => d.name).join(', ')}`)
```Combining with Animations
与动画结合使用
Reveal Then Edit
先展示再编辑
markdown
<v-click>
```typescript {monaco}
// Code appears on click, then is editable
function greet(name: string) {
return `Hello, ${name}!`
}
```
</v-click>markdown
<v-click>
```typescript {monaco}
// 点击后显示代码,随后可编辑
function greet(name: string) {
return `Hello, ${name}!`
}
```
</v-click>Step-by-Step with Monaco
结合动画分步展示
markdown
<v-clicks>
Start with this code:
```typescript {monaco}
const x = 1
```
Then try adding more lines!
</v-clicks>markdown
<v-clicks>
从这段代码开始:
```typescript {monaco}
const x = 1
```
然后尝试添加更多代码行!
</v-clicks>Best Practices
最佳实践
1. Keep Examples Focused
1. 示例聚焦单一概念
markdown
```typescript {monaco-run}
// GOOD: Single concept
const sum = [1, 2, 3].reduce((a, b) => a + b, 0)
console.log(sum) // 6
```markdown
```typescript {monaco-run}
// 良好示例:仅展示单一概念
const sum = [1, 2, 3].reduce((a, b) => a + b, 0)
console.log(sum) // 6
```2. Provide Starting Point
2. 提供初始代码模板
markdown
```typescript {monaco-run}
// Complete the function:
function capitalize(str: string): string {
// Your code here
return str
}
console.log(capitalize('hello')) // Should print: 'Hello'
```markdown
```typescript {monaco-run}
// 补全这个函数:
function capitalize(str: string): string {
// 在此处编写代码
return str
}
console.log(capitalize('hello')) // 应输出: 'Hello'
```3. Show Expected Output
3. 标注预期输出
markdown
```typescript {monaco-run}
// Code example
const result = [1, 2, 3].map(n => n ** 2)
console.log(result)
// Expected output: [1, 4, 9]
```markdown
```typescript {monaco-run}
// 代码示例
const result = [1, 2, 3].map(n => n ** 2)
console.log(result)
// 预期输出: [1, 4, 9]
```4. Handle Errors Gracefully
4. 优雅处理错误
markdown
```typescript {monaco-run}
try {
const result = riskyOperation()
console.log(result)
} catch (error) {
console.error('Error:', error.message)
}
function riskyOperation() {
// Might throw an error
throw new Error('Oops!')
}
```markdown
```typescript {monaco-run}
try {
const result = riskyOperation()
console.log(result)
} catch (error) {
console.error('Error:', error.message)
}
function riskyOperation() {
// 可能会抛出错误
throw new Error('Oops!')
}
```Limitations
限制说明
- No DOM Access: Cannot manipulate the page DOM
- Limited APIs: Only standard JavaScript APIs available
- No Imports: Cannot import external packages
- Console Only: Output is console-based
- 无DOM访问权限:无法操作页面DOM
- API受限:仅支持标准JavaScript API
- 无法导入外部包:不能引入外部依赖
- 仅支持控制台输出:输出内容仅在控制台显示
Output Format
输出格式规范
When creating Monaco code blocks:
PURPOSE: [What the code demonstrates]
INTERACTION: [How audience should interact]
CODE:
```[language] {monaco-run}
// Clear comments explaining purpose
[Code with good defaults]
// Expected output notedSUGGESTED EDITS:
- Try changing X to Y
- Modify function to do Z
undefined创建Monaco代码块时,请遵循以下格式:
用途: [代码演示的内容]
交互方式: [观众应如何操作]
代码:
```[language] {monaco-run}
// 清晰的注释说明代码用途
[带有合理默认值的代码]
// 标注预期输出建议修改方向:
- 尝试将X改为Y
- 修改函数实现Z功能
undefined