Monaco Editor 自定義語言的實現

廢話很少說javascript

The Monaco Editor is the code editor that powers VS Code.css

It is licensed under the MIT License and supports IE 9/10/11, Edge, Chrome, Firefox, Safari and Opera.
html


安裝

npm install monaco-editor複製代碼

引用

本人寫Vue + Webpack 較多,以此爲例:vue

第一種寫法: 使用  monaco-editor-webpack-pluginjava

// .vue 對應的 script腳本中
import * as monaco from 'monaco-editor';

monaco.editor.create(document.getElementById('container'), {
  value: [
    'function x() {',
    '\tconsole.log("Hello world!");',
    '}'
  ].join('\n'),
  language: 'javascript'
});複製代碼
// 在 webpack.base.conf.js 中
// 須要安裝 monaco-editor-webpack-plugin

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const path = require('path');
module.exports = {
  ...
  plugins: [
    new MonacoWebpackPlugin()
  ]
};
複製代碼


第二種寫法:webpack

// .vue 對應的 script腳本中

import * as monaco from 'monaco-editor';

// Since packaging is done by you, you need
// to instruct the editor how you named the
// bundles that contain the web workers.
self.MonacoEnvironment = {
  getWorkerUrl: function (moduleId, label) {
    if (label === 'json') {
      return './json.worker.bundle.js';
    }
    if (label === 'css') {
      return './css.worker.bundle.js';
    }
    if (label === 'html') {
      return './html.worker.bundle.js';
    }
    if (label === 'typescript' || label === 'javascript') {
      return './ts.worker.bundle.js';
    }
    return './editor.worker.bundle.js';
  }
}

monaco.editor.create(document.getElementById('container'), {
  value: [
    'function x() {',
    '\tconsole.log("Hello world!");',
    '}'
  ].join('\n'),
  language: 'javascript'
});複製代碼
// 在 webpack.base.conf.js 中
// 不須要安裝任何腳本const path = require('path');

module.exports = {
  entry: {
    "app": './index.js',
    // Package each language's worker and give these filenames in `getWorkerUrl` "editor.worker": 'monaco-editor/esm/vs/editor/editor.worker.js', "json.worker": 'monaco-editor/esm/vs/language/json/json.worker', "css.worker": 'monaco-editor/esm/vs/language/css/css.worker', "html.worker": 'monaco-editor/esm/vs/language/html/html.worker', "ts.worker": 'monaco-editor/esm/vs/language/typescript/ts.worker', }, ... };複製代碼

 自定義語言

本人使用的是第二種方式,引用Editor。因爲須要自定義語言 ,因此值引用了一個editor.worker包。git

webpack.base.conf.js中的配置github

module.exports = {
  entry: {
    app: ['babel-polyfill', './src/main.js'], // './src/main.js'
    "editor.worker": 'monaco-editor/esm/vs/editor/editor.worker.js',  }
 ......
}複製代碼

.vue 文件對應的script代碼段,引用monaco-editor,web

引入custom-language 和 custom-completion正則表達式

import * as monaco from 'monaco-editor'
import vLang from './custom-language'
import vCompletion from './custon-completion'

initEditor () {
      // 在methods中定義的編輯器初始化方法
      this.MonacoEnvironment = {
        getWorkerUrl: function (moduleId, label) {
          return './editor.worker.bundle.js'
        }
      }
      // 註冊自定義語言
      monaco.languages.register({ id: 'mySpecialLanguage' })
      // 爲該自定義語言基本的Token
      monaco.languages.setMonarchTokensProvider('mySpecialLanguage', vLang)
      // 爲該語言註冊一個語言提示器--聯想
      monaco.languages.registerCompletionItemProvider('mySpecialLanguage', {        provideCompletionItems: () => {          return { suggestions: vCompletion }        }      })
      // 建立編輯器
      this.vEditor.editor = monaco.editor.create(document.getElementById('editor'), {
        value: this.vEditor.value,
        theme: this.vEditor.theme,
        language: 'mySpecialLanguage',
      })
    },複製代碼

// custom-language.js
  /* eslint-disable no-useless-escape */
export default {
  // Set defaultToken to invalid to see what you do not tokenize yet
  // defaultToken: 'invalid',
  keywords: [    'IF', 'THEN', 'END', 'WHILE', 'DO', 'ELSE'  ],
  typeKeywords: [],
  operators: ['=', '>', '<', '==', '<=', '>=', '!=', '<>', '+', '-', '*', '/'],
  digits: /\d+(_+\d+)*/,
  octaldigits: /[0-7]+(_+[0-7]+)*/,  binarydigits: /[0-1]+(_+[0-1]+)*/,
  hexdigits: /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,
  // The main tokenizer for our languages
  tokenizer: {
    root: [
      // identifiers and keywords
      [/[a-z_$][\w$]*/, {
        cases: {
          '@typeKeywords': 'keyword',
          '@keywords': 'keyword',
          '@default': 'identifier'
        }
      }],
      [/[A-Z][\w\$]*/, 'type.identifier'],  // to show class names nicely
      // whitespace
      { include: '@whitespace' },
      // delimiters and operators
      [/[{}()\[\]]/, '@brackets'],
      // @ annotations.
      // As an example, we emit a debugging log message on these tokens.
      // Note: message are supressed during the first load -- change some lines to see them.
      // eslint-disable-next-line no-useless-escape
      [/@\s*[a-zA-Z_\$][\w\$]*/, { token: 'annotation', log: 'annotation token: $0' }],
      // numbers
      [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
      [/0[xX][0-9a-fA-F]+/, 'number.hex'],
      [/\d+/, 'number'],
      // delimiter: after number because of .\d floats
      [/[;,.]/, 'delimiter'],
      // strings
      [/"([^"\\]|\\.)*$/, 'string.invalid'],
      // non-teminated string
      [/"/, { token: 'string.quote', bracket: '@open', next: '@string' }], // characters [/'[^\\']'/, 'string'], [/'/, 'string.invalid'] ], comment: [ [/[^\/*]+/, 'comment'], [/\/\*/, 'comment', '@push'], // nested comment ['\\*/', 'comment', '@pop'], [/[\/*]/, 'comment'] ], string: [ [/[^\\"]+/, 'string'],
      [/\\./, 'string.escape.invalid'],
      [/"/, { token: 'string.quote', bracket: '@close', next: '@pop' }] ], whitespace: [ [/[ \t\r\n]+/, 'white'], [/\/\*/, 'comment', '@comment'], [/\/\/.*$/, 'comment'], ], },} 複製代碼

// custom-completion.js
/* eslint-disable no-template-curly-in-string */
export default [  
 /**   * 內置函數   */  
 {    
    label: 'getValue',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getValue(${1:pattern})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '根據pattern描述的正則表達式,從數據項中獲取匹配的字符串'
  },  {    
    label: 'getIniString',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getIniString(${1:sec}, ${2: key})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '從ini類型的數據中,根據section和key,獲取key對應的值,做爲字符串返回'
  },  {
    label: 'getIniInt',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getIniInt(${1:sec}, ${2: key})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '從ini類型的數據中,根據section和key,獲取key對應的值,,做爲整數返回'
  },  {
    label: 'getIniDouble',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getIniDouble(${1:sec}, ${2: key})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '從ini類型的數據中,根據section和key,獲取key對應的值,做爲浮點數返回'
  },  {
    label: 'isEmpty',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'isEmpty(${1:str})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '判斷str是否爲空'
  },  {
    label: 'isEqual',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'isEqual(${1:str1}, ${2: str2})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '判斷str是否爲空'
  },  {
    label: 'isContain',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'isContain(${1:str})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '判斷數據項中是否包含str'
  }, {
    label: 'getJsonInt',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getJsonInt(${1:path})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '根據path獲取JSON數據中做爲整數返回的值'
  },  {
    label: 'getJsonDouble',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getJsonDouble(${1:path})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '根據path獲取JSON數據中做爲整數返回的值'
  },  {
    label: 'getJsonSize',
    kind: monaco.languages.CompletionItemKind.Function,
    insertText: 'getJsonSize(${1:path})',
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: '根據path獲取JSON數據中做爲數組類型的數據的長度'
  },
  /**   * 語句   */  
  {
    label: 'IF-ELSE',
    kind: monaco.languages.CompletionItemKind.Snippet,
    insertText: [      
      'IF ${1:condition} THEN',
      '\t$0',
      'ELSE',
      '\t$0',
      'END'
    ].join('\n'),
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: 'If-Else Statement'
  },  {
    label: 'WHILE-DO',
    kind: monaco.languages.CompletionItemKind.Snippet,
    insertText: [
      'WHILE ${1:condition} DO',
      '\t$0',
      'END'
    ].join('\n'),
    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
    documentation: 'WHILE-DO Statement'
  }]

複製代碼

截圖:


想要更多信息,仍是看看官網和stackoverflow

官網說明:

官網地址:microsoft.github.io/monaco-edit…

自定義語言的DEMO:microsoft.github.io/monaco-edit…

在webpack類的項目中如何引用:github.com/Microsoft/m…

相關文章
相關標籤/搜索