Skip to content

Commit c66513b

Browse files
committed
feat(monaco): types auto discovery for TypeScript monaco
1 parent 936e2e0 commit c66513b

File tree

3 files changed

+19
-13
lines changed

3 files changed

+19
-13
lines changed

packages/client/setup/monaco.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ const setup = createSingletonPromise(async() => {
1515
})
1616

1717
await Promise.all([
18-
// @ts-expect-error
19-
import('/@monaco-types/vue'),
20-
// @ts-expect-error
21-
import('/@monaco-types/@vueuse/core'),
2218
// load workers
2319
(async() => {
2420
const [

packages/slidev/node/plugins/monaco.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Plugin, resolvePackageData } from 'vite'
22
import base64 from 'js-base64'
3+
import { isTruthy } from '@slidev/client/node_modules/@antfu/utils/dist'
34

45
export function createMonacoLoader(): Plugin {
56
return {
@@ -34,15 +35,28 @@ export function createMonacoLoader(): Plugin {
3435
}
3536
}
3637

37-
export function transformMarkdownMonaco(code: string) {
38+
export function transformMarkdownMonaco(md: string) {
39+
const typeModules = new Set<string>()
40+
3841
// transform monaco
39-
code = code.replace(/\n```(\w+?){monaco([\w:,-]*)}[\s\n]*([\s\S]+?)\n```/mg, (full, lang = 'ts', options: string, code: string) => {
42+
md = md.replace(/\n```(\w+?){monaco([\w:,-]*)}[\s\n]*([\s\S]+?)\n```/mg, (full, lang = 'ts', options: string, code: string) => {
4043
options = options || ''
41-
code = base64.encode(code, true)
42-
return `<Monaco :code="'${code}'" :lang="'${lang}'" :readonly="${options.includes('readonly')}" />`
44+
lang = lang.trim()
45+
if (lang === 'ts' || lang === 'typescript') {
46+
Array.from(code.matchAll(/\s+from\s+(["'])([\/\w@-]+)\1/g))
47+
.map(i => i[2])
48+
.filter(isTruthy)
49+
.map(i => typeModules.add(i))
50+
}
51+
const encoded = base64.encode(code, true)
52+
return `<Monaco :code="'${encoded}'" lang="${lang}" :readonly="${options.includes('readonly')}" />`
4353
})
4454

45-
return code
55+
// types auto discovery for TypeScript monaco
56+
if (typeModules.size)
57+
md += `\n<script setup>\n${Array.from(typeModules).map(i => `import('/@monaco-types/${i}')`).join('\n')}\n</script>\n`
58+
59+
return md
4660
}
4761

4862
export function truncateMancoMark(code: string) {

packages/theme-default/setup/monaco.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,6 @@ import * as monaco from 'monaco-editor'
22

33
export default async function setupMonaco() {
44
await Promise.all([
5-
// @ts-expect-error
6-
import('/@monaco-types/vue'),
7-
// @ts-expect-error
8-
import('/@monaco-types/@vueuse/core'),
95
// load theme
106
(async() => {
117
const { default: dark } = await import('theme-vitesse/themes/vitesse-dark.json')

0 commit comments

Comments
 (0)