如何在 Vue 项目中使用 Monaco Editor

工具利器 Feb 19, 2020

如何在 Vue 项目中使用 Monaco Editor

Monaco Editor 是一款开源的在线代码编辑器。它是 VSCode 的浏览器版本,随着近年 VSCode 大热,Monaco Editor 也随之走红。它的使用也很简单,但按照其官方文档操作,在现代化框架如 Vue 中使用,会遇到一些问题;本文即根据踩过些坑,介绍一种在 Vue 项目中完好使用 Monaco Editor 可行的方案。

存在问题方案

按照其官方文档介绍,需要两部操作:1. 编写逻辑代码,2. Webpack 配置;具体操作可以参见 monaco-editor#option-2-using-plain-webpack。但在实际使用中,要么不能正常完美使用(如编写没有代码提示),要么会报错,官方也未给出解决方案;具体信息如下(也可以参见 Github Issues:Error: Unexpected usage (integration with vue)Uncaught Error: Unexpected usage #1690):

Error: Unexpected usage at EditorSimpleWorker.push../node_modules/monacoeditor/esm/vs/editor/common/services/editorSimpleWorker.js.EditorSimpleWorker.loadForeignModule ...

更合适的方案

使用 monaco-editor-webpack-plugin Webpack 插件,即可完美规避如上问题,具体可以参见如下代码:

  • 安装插件
yarn add monaco-editor-webpack-plugin --dev
# Or
npm i monaco-editor-webpack-plugin --save-dev
  • vue.config.js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')

module.exports = {
  // ......
  configureWebpack: {
    plugins: [
      new MonacoWebpackPlugin({
        // available options are documented at https://github.com/Microsoft/monaco-editor-webpack-plugin#options
        languages: ['javascript', 'css', 'html', 'typescript', 'json']
      })
    ]
  }
}
  • index.js
import * as monaco from 'monaco-editor'
import 'monaco-editor/esm/vs/editor/contrib/find/findController.js'

editor = monaco.editor.create(dom, {
  fontSize: '14px',
  language: 'html',
  folding: true,
  foldingStrategy: 'indentation', // 代码可分小段折叠  
  automaticLayout: true, // 自适应布局  
  overviewRulerBorder: false, // 不要滚动条的边框  
  scrollBeyondLastLine: false, // 取消代码后面一大段空白  
  minimap: {
    // 不要小地图  
    enabled: false
  }
})

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.