使用monaco編輯預覽markdown檔案

卓能文發表於2024-08-08

本打算使用remark來解析markdown的,但vite無論如何都不能編譯成功,總是缺少一堆相關依賴,並且npm上還找不到相關的包,估計是版本依賴關係問題,暫時沒時間來檢查修改問題,遂採用marked來解析。

<div>
    toolbar
</div>
<div style="display: flex; height: 40vh">
    <div style="flex: 50%; height: 100%">
        <div id="editor" style="height: 100%; width: 100%;"></div>
    </div>
    <div style="flex: 50%; height: 100%">
        <div id="previewer" style="height: 100%; width: 100%; overflow: auto"></div>
    </div>
</div>
<script type="module">
    import * as monaco from "monaco-editor";
    import { marked } from "marked";

    let content = "# Hello";
    let editor = monaco.editor.create(document.getElementById("editor"), {
        automaticLayout: true,
        language: "markdown",
        value: content,
        wordWrap: "on",
        wrappingIndent: "same",
    });

    editor.onDidChangeModelContent((e) => {
        preview();
    });

    function preview() {
        content = editor.getValue();
        const html = marked.parse(content);
        document.getElementById("previewer").innerHTML = html;
    }
</script>

相關文章