|
| 1 | +import * as monaco from 'monaco-editor'; |
| 2 | +import React, { useEffect, useRef } from 'react'; |
| 3 | + |
| 4 | +const MONACO_EDITOR_OPTIONS = { |
| 5 | + automaticLayout: true, |
| 6 | + scrollBeyondLastLine: false, |
| 7 | + fixedOverflowWidgets: true, |
| 8 | + theme: 'vs-dark', |
| 9 | + language: 'javascript', |
| 10 | +} as monaco.editor.IEditorConstructionOptions; |
| 11 | + |
| 12 | +self.MonacoEnvironment = { |
| 13 | + getWorker(_: string, label: string) { |
| 14 | + if (label === 'json') { |
| 15 | + return new Worker(new URL('monaco-editor/esm/vs/language/json/json.worker', import.meta.url)); |
| 16 | + } |
| 17 | + if (label === 'css' || label === 'scss' || label === 'less') { |
| 18 | + return new Worker(new URL('monaco-editor/esm/vs/language/css/css.worker', import.meta.url)); |
| 19 | + } |
| 20 | + if (label === 'html' || label === 'handlebars' || label === 'razor') { |
| 21 | + return new Worker(new URL('monaco-editor/esm/vs/language/html/html.worker', import.meta.url)); |
| 22 | + } |
| 23 | + if (label === 'typescript' || label === 'javascript') { |
| 24 | + return new Worker( |
| 25 | + new URL('monaco-editor/esm/vs/language/typescript/ts.worker', import.meta.url), |
| 26 | + ); |
| 27 | + } |
| 28 | + return new Worker(new URL('monaco-editor/esm/vs/editor/editor.worker', import.meta.url)); |
| 29 | + }, |
| 30 | +}; |
| 31 | + |
| 32 | +function Editor() { |
| 33 | + const editor_ref = useRef<HTMLDivElement>(null); |
| 34 | + |
| 35 | + useEffect(() => { |
| 36 | + if (editor_ref.current) { |
| 37 | + const editor = monaco.editor.create(editor_ref.current, { |
| 38 | + value: `const text = "Hello World";`, |
| 39 | + ...MONACO_EDITOR_OPTIONS, |
| 40 | + }); |
| 41 | + |
| 42 | + editor.onDidChangeModelContent(() => { |
| 43 | + const value = editor.getValue(); |
| 44 | + console.log(value); |
| 45 | + }); |
| 46 | + } |
| 47 | + }, []); |
| 48 | + |
| 49 | + return ( |
| 50 | + <div id="monaco_editor" style={{ flex: 1, margin: 30, height: '600px' }} ref={editor_ref} /> |
| 51 | + ); |
| 52 | +} |
| 53 | + |
| 54 | +export default React.memo(Editor); |
0 commit comments