使用monaco-editor浏览器代码编辑器

发布时间 2023-07-06 10:03:51作者: 妞妞猪

1.安装依赖

npm i monaco-editor

npm i monaco-editor-webpack-plugin

2.使用示例

<!-- 代码编辑器控件 -->
<template>
  <div id="monacoEditorContainer" style="width: 100%; height: 300px">
  </div>
</template>
 
<script>
import * as monaco from "monaco-editor";
export default {
    data() {
      return {
        standaloneEditorConstructionOptions: {
          value: '', // 编辑器的值
          language: 'javascript', //语言
          theme: 'vs-dark', // 编辑器主题:vs, hc-black, or vs-dark
          autoIndent: true, // 自动缩进
          readOnly: false, // 是否只读
        }
      };
    },
    mounted() {
      this.createMonacoEditor();
    },
    methods: {
      createMonacoEditor() {
        // 使用 - 创建 monacoEditor 对象
        const container = document.querySelector('#monacoEditorContainer')
        this.monacoEditor = monaco.editor.create(container, this.standaloneEditorConstructionOptions)
      },
    },
}
</script>
 需要注意的是要在vue.config.js中配置一下

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')

  module.exports = {

    configureWebpack: {

    plugins: [

      new MonacoWebpackPlugin()

    ]

    }

  }

这样就可以有提示了

 然后在页面中引用控件

 <template>
<codeEdit
            ref="html"
            width="500px"
            height="290px"
            language="html" />
        <el-button @click="runCode">运行</el-button>
        <p>实现结果:</p>
        <iframe class="view-panel" id="preview" frameborder="0"></iframe>
</template>
<script>
....
methods:{
runCode() {
        var html = this.$refs.html.monacoEditor.getValue();
        // var css = this.$refs.css.monacoEditor.getValue();
        // var js = this.$refs.js.monacoEditor.getValue();
        let code = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Editor</title>
        </head>
        <body>${html}</body>

        </html>
       `;
        console.log(code);
        const preview = document.querySelector("#preview");
        preview.setAttribute("srcdoc", code);
      },
}
....
</script>
参考 https://www.codetd.com/article/14982206