|
1 | 1 | import { Plugin, resolvePackageData } from 'vite'
|
2 | 2 | import base64 from 'js-base64'
|
| 3 | +import { isTruthy } from '@slidev/client/node_modules/@antfu/utils/dist' |
3 | 4 |
|
4 | 5 | export function createMonacoLoader(): Plugin {
|
5 | 6 | return {
|
@@ -34,15 +35,28 @@ export function createMonacoLoader(): Plugin {
|
34 | 35 | }
|
35 | 36 | }
|
36 | 37 |
|
37 |
| -export function transformMarkdownMonaco(code: string) { |
| 38 | +export function transformMarkdownMonaco(md: string) { |
| 39 | + const typeModules = new Set<string>() |
| 40 | + |
38 | 41 | // 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) => { |
40 | 43 | 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')}" />` |
43 | 53 | })
|
44 | 54 |
|
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 |
46 | 60 | }
|
47 | 61 |
|
48 | 62 | export function truncateMancoMark(code: string) {
|
|
0 commit comments