Skip to main content

monaco-editor

vue3 中使用

直接引入

参阅资料:https://blog.csdn.net/weixin_49684489/article/details/132456716

安装到项目

npm install monaco-editor --save

# vite 打包支持 ( 必须安装)
npm install --save-dev vite-plugin-monaco-editor
// vite.config.js
import monacoEditorPlugin from "vite-plugin-monaco-editor"
plugins: [
// monacoEditorPlugin() 不能不写{}配置项 会报 Cannot read properties of undefined (reading 'languageWorkers')这个错
monacoEditorPlugin({ languages: ['javascript', 'typescript', 'html', 'css', 'json','java','sql','groovy','shell','python']}),
],

页面使用

<template>
<div>
<a-select style="width: 120px" @change="handelChange">
<a-select-option v-for="(item,index) in languageList" :key="index" :value="item">
{{ item }}
</a-select-option>
</a-select>
<button @click="handleBtn">获取</button>
<button @click="handleForrmat">格式化</button>
<button @click="handelSet">设置值</button>
<div ref="main" style="width: 100%; height: 600px"></div>
</div>
</template>

<script setup>
import * as monaco from "monaco-editor";
import { toRaw, onMounted, ref } from "vue";
const monacoEditor = ref(undefined);
const main = ref(null);
let languageList=ref([
'javascript', 'json', 'sql', 'java', 'groovy', 'shell', 'python'
])
onMounted(() => {
init();
});
const handleForrmat = () => {
monacoEditor.value.getAction('editor.action.formatDocument').run()
};
const handleBtn = () => {
let demo = toRaw(monacoEditor.value).getValue(); //获取编辑器中的文本
console.log(demo)
};
const handelChange = (val) => {
monaco.editor.setModelLanguage(monacoEditor.value.getModel(), val)
}
const handelSet=()=>{
toRaw(monacoEditor.value).setModel(monaco.editor.createModel(`{"name":'123'}`,'json'))
}
const init = () => {
// 使用 - 创建 monacoEditor 对象
monacoEditor.value = monaco.editor.create(main.value, {
theme: "hc-black", // 主题
language: "json",
renderLineHighlight: "gutter",
folding: true, // 是否折叠
roundedSelection: false,
foldingHighlight: true, // 折叠等高线
foldingStrategy: "indentation", // 折叠方式 auto | indentation
showFoldingControls: "always", // 是否一直显示折叠 always | mouseover
disableLayerHinting: true, // 等宽优化
emptySelectionClipboard: false, // 空选择剪切板
selectionClipboard: false, // 选择剪切板
automaticLayout: true, // 自动布局
codeLens: true, // 代码镜头
scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
colorDecorators: true, // 颜色装饰器
accessibilitySupport: "on", // 辅助功能支持 "auto" | "off" | "on"
lineNumbers: "on", // 行号 取值: "on" | "off" | "relative" | "interval" | function
lineNumbersMinChars: 5, // 行号最小字符 number
enableSplitViewResizing: false,
readOnly: false, //是否只读 取值 true | false
});
};
</script>


使用@monaco-editor/loader(适合浏览器)

创建hook组件./useMonacoEditor.ts

/*
* @Author: CPS holy.dandelion@139.com
* @Date: 2023-09-16 19:43:06
* @LastEditors: CPS holy.dandelion@139.com
* @LastEditTime: 2023-09-16 19:43:47
* @FilePath: \YYS-cuter-client2\src\renderer\src\views\NsNpcManager\_conponents\useMonacoEditor.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*
*
* @example
import { useMonacoEditor } from '@/hooks/useMonacoEditor'
const { monacoRef, initMonaco } = useMonacoEditor()

onMounted(async()=>{
await initMonaco()
monacoRef.value.editor.create(document.getElementById('container'), {
value: "function hello() {\n\talert('Hello world!');\n}",
language: 'javascript'
});
})
*
*/
import loader from "@monaco-editor/loader"
import { ref } from "vue"

const monacoRef = ref<any>(null)
const monacoLoader = loader.init()

const initMonaco = () => {
return new Promise<void>((resolve, reject) => {
if (monacoRef.value) {
resolve()
return
}
monacoLoader
.then((monacoInstance) => {
monacoRef.value = monacoInstance
})
.catch((error) => {
if (error?.type !== "cancelation") {
console.error("Monaco initialization error:", error)
reject()
}
})
})
}

export function useMonacoEditor() {
return {
initMonaco,
monacoRef,
}
}

使用

// xxx.vue
<template>
<div ref="monacoRef" :class="['w-[500px] h-[500px]', 'bg-red-200']"></div>
</template>

<script setup lang="ts">
import { useMonacoEditor } from "./useMonacoEditor"
const { monacoRef, initMonaco } = useMonacoEditor()

onMounted(async () => {
await initMonaco()
monacoRef.value.editor.create(document.getElementById("container"), {
value: "function hello() {\n\talert('Hello world!');\n}",
language: "javascript",
})
})
</script>

配置选项

this.editor = monaco.editor.create(this.$refs.editor, {
acceptSuggestionOnCommitCharacter: true, // 接受关于提交字符的建议
acceptSuggestionOnEnter: 'on', // 接受输入建议 "on" | "off" | "smart"
accessibilityPageSize: 10, // 辅助功能页面大小 Number 说明:控制编辑器中可由屏幕阅读器读出的行数。警告:这对大于默认值的数字具有性能含义。
accessibilitySupport: 'on', // 辅助功能支持 控制编辑器是否应在为屏幕阅读器优化的模式下运行。
autoClosingBrackets: 'always', // 是否自动添加结束括号(包括中括号) "always" | "languageDefined" | "beforeWhitespace" | "never"
autoClosingDelete: 'always', // 是否自动删除结束括号(包括中括号) "always" | "never" | "auto"
autoClosingOvertype: 'always', // 是否关闭改写 即使用insert模式时是覆盖后面的文字还是不覆盖后面的文字 "always" | "never" | "auto"
autoClosingQuotes: 'always', // 是否自动添加结束的单引号 双引号 "always" | "languageDefined" | "beforeWhitespace" | "never"
autoIndent: 'None', // 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
automaticLayout: true, // 自动布局
codeLens: false, // 是否显示codeLens 通过 CodeLens,你可以在专注于工作的同时了解代码所发生的情况 – 而无需离开编辑器。 可以查找代码引用、代码更改、关联的 Bug、工作项、代码评审和单元测试。
codeLensFontFamily: '', // codeLens的字体样式
codeLensFontSize: 14, // codeLens的字体大小
colorDecorators: false, // 呈现内联色彩装饰器和颜色选择器
comments: {
ignoreEmptyLines: true, // 插入行注释时忽略空行。默认为真。
insertSpace: true // 在行注释标记之后和块注释标记内插入一个空格。默认为真。
}, // 注释配置
contextmenu: true, // 启用上下文菜单
columnSelection: false, // 启用列编辑 按下shift键位然后按↑↓键位可以实现列选择 然后实现列编辑
autoSurround: 'never', // 是否应自动环绕选择
copyWithSyntaxHighlighting: true, // 是否应将语法突出显示复制到剪贴板中 即 当你复制到word中是否保持文字高亮颜色
cursorBlinking: 'Solid', // 光标动画样式
cursorSmoothCaretAnimation: true, // 是否启用光标平滑插入动画 当你在快速输入文字的时候 光标是直接平滑的移动还是直接"闪现"到当前文字所处位置
cursorStyle: 'UnderlineThin', // "Block"|"BlockOutline"|"Line"|"LineThin"|"Underline"|"UnderlineThin" 光标样式
cursorSurroundingLines: 0, // 光标环绕行数 当文字输入超过屏幕时 可以看见右侧滚动条中光标所处位置是在滚动条中间还是顶部还是底部 即光标环绕行数 环绕行数越大 光标在滚动条中位置越居中
cursorSurroundingLinesStyle: 'all', // "default" | "all" 光标环绕样式
cursorWidth: 2, // <=25 光标宽度
minimap: {
enabled: false // 是否启用预览图
}, // 预览图设置
folding: true, // 是否启用代码折叠
links: true, // 是否点击链接
overviewRulerBorder: false, // 是否应围绕概览标尺绘制边框
renderLineHighlight: 'gutter', // 当前行突出显示方式
roundedSelection: false, // 选区是否有圆角
scrollBeyondLastLine: false, // 设置编辑器是否可以滚动到最后一行之后
readOnly: false, // 是否为只读模式
theme: 'vs'// vs, hc-black, or vs-dark
})


参阅资料