前端工具 | JS編譯器Monaco使用教程
- 2021 年 6 月 8 日
- 筆記
- monaco-editor, vue-monaco-editor, webJSeditor, 插件
前言
我的需求是可以語法高亮、函數提示功能、自動換行、代碼摺疊
Monaco
Monaco是微軟家的,支持的語言很多,還有縮略地圖,有時候提示不好用然後包體很大。
The Monaco Editor is the code editor that powers VS Code.
使用方法
- 官網
[官方文檔](//microsoft.github.io/monaco-editor/index.html)
[在線demo](//github.com/Microsoft/monaco-editor-samples)
[github](//github.com/Microsoft/monaco-editor)
- 安裝
yarn add monaco-editor | npm install monaco-editor
- 引入
import * as monaco from 'monaco-editor' // 包體很大了 但是demo可以跑起來
//自定義一些提示函數
const suggestions = [
{
label: 'split_chinese',
insertText: 'split_chinese(inputString,language);', // 不寫的時候不展示。。
detail:
'inputString:need split string\n' +
'language:\nCH_T:traditional Chinese\nCH_S:Chinese Simplified\n HK_T:Hong Kong Traditional\nTW_T:Taiwan Traditional\n'
},
{
label: 'uuid',
insertText: 'var uuid = uuid();',
detail: 'generate uuid'
},
{
label: 'HashMap',
insertText: 'var hashMap = new HashMap();',
detail: 'create hash object'
}
]
- 初始化
mounted() {
monaco.languages.registerCompletionItemProvider('JavaScript', {
provideCompletionItems() {
return {
suggestions: suggestions
}
},
triggerCharacters: [' ', '.'] // 寫觸發提示的字符,可以有多個
})
let self = this
setTimeout(function () {
self.init()
}, 50) //因為父組件還未傳參 子組件已經渲染
}
//初始化方法
init(script) {
let self = this
if (script) this.code = script
self.$refs.container.innerHTML = ''
var editor = monaco.editor.create(this.$refs.container, {
value: this.code,
language: 'javascript',
minimap: {
enabled: false
},
fontSize: '12px',
fixedOverflowWidgets: true // 超出編輯器大小的使用fixed屬性顯示
})
editor.onDidChangeModelContent(function () {
self.$emit('update:code', editor.getValue()) //用來監聽編輯器內容變化,將內容傳給父組件
})
}
- html
<template>
<div ref="container" class="monaco"></div>
</template>
- css
<style scoped>
.monaco {
width: 95%;
height: 400px;
border: 1px solid #dcdfe6;
text-align: left;
margin-right: 20px;
border-radius: 4px;
}
</style>
- 運行效果
缺點
我的推翻了,不想再跑一下,代碼還在就寫一個demo。運行還是可以的(有客戶使用但也反饋不好用,是我自己的鍋,不配使用Monaco)真的很難用,特別是提示的功能,一般情況下是沒有提示的。然後一個包很大,好像有3.9G(嚴重)。可能沒有按需引入,但是不引入沒有提示功能,自定義函數提示。還有webpack配置,來回折騰!
芳妮醬總結
今天我們改用了brace,真香。使用簡單,基本需求滿足,沒有額外的配置