JS代码编译器Monaco使用方法

2022-04-15 0 1,100

前言

我的需求是可以语法高亮、函数提示功能、自动换行、代码折叠

Monaco

Monaco是微软家的,支持的语言很多,还有缩略地图,有时候提示不好用然后包体很大。
The Monaco Editor is the code editor that powers VS Code.

JS代码编译器Monaco使用方法

使用方法官网

[官方文档](https://microsoft.github.io/monaco-editor/index.html)
[在线demo](https://github.com/Microsoft/monaco-editor-samples)
[github](https://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>

 

运行效果

JS代码编译器Monaco使用方法

缺点

我的推翻了,不想再跑一下,代码还在就写一个demo。运行还是可以的(有客户使用但也反馈不好用,是我自己的锅,不配使用Monaco)真的很难用,特别是提示的功能,一般情况下是没有提示的。然后一个包很大,好像有3.9G(严重)。可能没有按需引入,但是不引入没有提示功能,自定义函数提示。还有webpack配置,来回折腾!

以上就是JS编译器Monaco使用教程的详细内容,更多关于JS编译器Monaco的资料请关注NICE源码其它相关文章!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript JS代码编译器Monaco使用方法 https://www.niceym.com/28651.html