JS在線代碼編輯器多種方案monaco-editor,vue-monaco-editor
- 2020 年 4 月 29 日
- 筆記
- edtior, monaco-editor, monaco-editor-webpack-plugin, VUE, vue-monaco-editor, webpack
前言
JavaScript在線代碼編輯器。
需要代碼提示,關鍵字高亮,能夠格式化代碼。(不需要在線運行)
簡簡單單的需求。
方案一: Monaco-editor
簡介:微軟的開源項目,開源中國上面的在線代碼編輯器也是用的這個(我就是順着藤爬到Monaco editor的)
有 『在線 VS code』 美稱
官網://microsoft.github.io/monaco-editor/
優點:多語言支持,代碼提示(內置函數蠻多的)。文檔很清晰,API很詳細了。更重要的是給出的案例非常多。
缺點:一開始摸不着頭腦(本人是在vue項目使用),靜態資源的引用是魔鬼(官方就是ES5方式資源引用),最好的方案是要搭配 webpack plugin 使用
找了那麼多的資料,沒見幾個demo寫的好(這也是我要再寫一篇的原因啦 爭取看到的人都可以快速上手)
源碼://github.com/Microsoft/monaco-editor
案例://github.com/Microsoft/monaco-editor-samples/ 一定要看這個,官方給你展示各種功能(一套git pull 下來,在本地環境直接看demo),
鬼知道我走了多少冤枉路。
本人案例展示,直接上源碼嗎?哈哈哈。


1 npm install monaco-edtior //安裝 2 3 test.vue //新建一個文件 4 <template> 5 <div ref="container" style="width:800px;height:600px;border:1px solid grey;text-align: left"></div> 6 </template> 7 8 <script> 9 import * as monaco from "monaco-editor"; // 包體很大了 但是demo可以跑起來 10 11 export default{ 12 mounted() { 13 var editor = monaco.editor.create(this.$refs.container, { 14 value: [ 15 'function x() {', 16 '\tconsole.log("Hello world!");', 17 '}' 18 ].join('\n'), 19 language: 'javascript', 20 minimap:{ 21 enabled:false 22 }, 23 selectOnLineNumbers: true, 24 roundedSelection: false, 25 cursorStyle: 'line', // 光標樣式 26 automaticLayout: false, // 自動布局 27 glyphMargin: true, // 字形邊緣 28 useTabStops: false, 29 fontSize: 16, // 字體大小 30 autoIndent: false //自動布局 31 }); 32 } 33 } 34 </script>
View Code
JavaScript 參考這個案例!!!
方案二 vue-monaco-editor(沒錯就是別人集成好的)
原因:monaco 按需求加載太難了,官方案例也是在靜態資源中引用 node_model中的(地獄來了)
針對這個有兩種解決方案
方案一:資源引用哪家強,就到前端找webpack
方案二:本人偷懶,直接用vue-Monaco-editor(Rect 有的)
再次上源碼,哈哈哈哈哈
方案一的源碼


npm install monaco-editor-webpack-plugin //安裝 const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin'); module.exports = { // ...... configureWebpack: { plugins: [ new MonacoWebpackPlugin({ // available options are documented at //github.com/Microsoft/monaco-editor-webpack-plugin#options languages: ['javascript', 'css', 'html', 'typescript', 'json'] }) ] } };
View Code
方案二的源碼


<template> <div id="app"> <MonacoEditor height="300" width="1200" class="vs" style="text-align: left;background-color: #fff" language="javascript" :code="code" :editorOptions="options" @mounted="onMounted" @codeChange="onCodeChange" > </MonacoEditor> </div> </template> <script> import MonacoEditor from 'vue-monaco-editor' export default { data() { return { code: '', editor:null, options: { theme: "vs", selectOnLineNumbers: true, roundedSelection: false, readOnly: false, automaticLayout: true, glyphMargin: true, showFoldingControls: "always", formatOnPaste: true, formatOnType: true, folding: true, } } }, components: { MonacoEditor }, methods:{ onMounted (editor) { this.editor = editor; }, onCodeChange(editor) {}, } } </script> <style> </style>
View Code
前方有坑
同一個項目裏面
既安裝了vue-monaco-editor 又安裝了Monaco-editor
然後 就不會智能提示了(2333)
這個問題,emmm(稍後解決吧,我再搞codemirror的)
算了codeMirror 再分一篇文章