返回 slidev
config-code-runners.md
根目录 / docs / custom / config-code-runners.md
1 # Configure Code Runners
2
3 <Environment type="client" />
4
5 Define code runners for custom languages in your Monaco Editor.
6
7 By default, JavaScript, TypeScript runners are supported built-in. They run in the browser **without** a sandbox environment. If you want more advanced integrations, you can provide your own code runner that sends the code to a remote server, runs in a Web Worker, or anything, up to you.
8
9 Create `./setup/code-runners.ts` with the following content:
10
11 ```ts twoslash [setup/code-runners.ts]
12 /* eslint-disable import/first */
13 declare const executePythonCodeRemotely: (code: string) => Promise<string>
14 declare const sanitizeHtml: (html: string) => string
15 // ---cut---
16 import { defineCodeRunnersSetup } from '@slidev/types'
17
18 export default defineCodeRunnersSetup(() => {
19 return {
20 async python(code, ctx) {
21 // Somehow execute the code and return the result
22 const result = await executePythonCodeRemotely(code)
23 return {
24 text: result
25 }
26 },
27 html(code, ctx) {
28 return {
29 html: sanitizeHtml(code)
30 }
31 },
32 // or other languages, key is the language id
33 }
34 })
35 ```
36
37 ## Runner Context
38
39 The second argument `ctx` is the runner context, which contains the following properties:
40
41 ```ts twoslash
42 import type { CodeRunnerOutputs } from '@slidev/types'
43 import type { CodeToHastOptions } from 'shiki'
44 // ---cut---
45 export interface CodeRunnerContext {
46 /**
47 * Options passed to runner via the `runnerOptions` prop.
48 */
49 options: Record<string, unknown>
50 /**
51 * Highlight code with shiki.
52 */
53 highlight: (code: string, lang: string, options?: Partial<CodeToHastOptions>) => string
54 /**
55 * Use (other) code runner to run code.
56 */
57 run: (code: string, lang: string) => Promise<CodeRunnerOutputs>
58 }
59 ```
60
61 ## Runner Output
62
63 The runner can either return a text or HTML output, or an element to be mounted. Refer to https://github.com/slidevjs/slidev/blob/main/packages/types/src/code-runner.ts for more details.
64
65 ## Additional Runner Dependencies
66
67 By default, Slidev will scan the Markdown source and automatically import the necessary dependencies for the code runners. If you want to manually import dependencies, you can use the `monacoRunAdditionalDeps` option in the [headmatter](./index#headmatter):
68
69 ```yaml
70 monacoRunAdditionalDeps:
71 - ./path/to/dependency
72 - lodash-es
73 ```
74
75 ::: tip
76 The paths are resolved relative to the `snippets` directory. And the names of the deps should be exactly the same as the imported ones in the code.
77 :::
78
78 lines MARKDOWN