Last active
November 17, 2024 07:53
-
-
Save ChinmayMoghe/671c2e741eb274e86e60e31b6a4a6dcd to your computer and use it in GitHub Desktop.
Sveltekit Monaco Editor - render monaco editor with SSR enabled for any page - (it will run the monaco editor code only on client side though)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { onDestroy, onMount } from 'svelte'; | |
import { browser } from '$app/environment'; | |
import type { editor } from 'monaco-editor'; | |
const extensions = { | |
json: ['json'], | |
css: ['css', 'less', 'scss'], | |
js: ['typescript', 'javascript'], | |
html: ['html', 'razor', 'handlebars'] | |
}; | |
let codeEditor = $state<editor.IStandaloneCodeEditor | null>(null); | |
let editorRef: HTMLDivElement; | |
onMount(async () => { | |
try { | |
// only run in client side - need to have dynamic imports since static imports will still be evaluated. | |
if (browser) { | |
const monaco = await import('monaco-editor'); | |
const editorWorker = (await import('monaco-editor/esm/vs/editor/editor.worker?worker')) | |
.default; | |
const jsonWorker = (await import('monaco-editor/esm/vs/language/json/json.worker?worker')) | |
.default; | |
const cssWorker = (await import('monaco-editor/esm/vs/language/css/css.worker?worker')) | |
.default; | |
const htmlWorker = (await import('monaco-editor/esm/vs/language/html/html.worker?worker')) | |
.default; | |
const tsWorker = (await import('monaco-editor/esm/vs/language/typescript/ts.worker?worker')) | |
.default; | |
self.MonacoEnvironment = { | |
getWorker: (_: string, label: string) => { | |
if (extensions.json.includes(label)) { | |
return new jsonWorker(); | |
} | |
if (extensions.html.includes(label)) { | |
return new htmlWorker(); | |
} | |
if (extensions.css.includes(label)) { | |
return new cssWorker(); | |
} | |
if (extensions.js.includes(label)) { | |
return new tsWorker(); | |
} | |
return new editorWorker(); | |
} | |
}; | |
monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true); | |
codeEditor = monaco.editor.create(editorRef, { | |
automaticLayout: true, | |
theme: 'vs-dark' | |
}); | |
} | |
} catch (error) { | |
console.log('bojack', error); | |
} | |
}); | |
onDestroy(() => { | |
codeEditor?.dispose(); | |
}); | |
</script> | |
<div class="editor-container" bind:this={editorRef}></div> | |
<style> | |
.editor-container { | |
width: 100%; | |
aspect-ratio: 1; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bare minimum code to run the monaco editor , you will need to add more code according to your use case in here