1.5.5 • Published 7 months ago

@guolao/vue-monaco-editor v1.5.5

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

monaco-vue

Use monaco-editor loaded from CDN in Vue 2&3, no need to bundling.

gitHub license npm version npm downloads

English | 简体中文

Why

The monaco-editor doesn't support ESM very well, which results in large files when the code is bundled.

But the official team has written a loader to lazy load files of the editor remotely, so we can load the files from a CDN to use it.

If you still want to import monaco-editor files from node_modules and bundle them into your code (without using remote loading), you will need to use a bundling tool. See here.

Installation

npm i @guolao/vue-monaco-editor

Vue <= 2.6.14 requires @vue/composition-api to be installed.

npm i @guolao/vue-monaco-editor @vue/composition-api

Don't forget to register the @vue/composition-api plugin!

import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'

Vue.use(VueCompositionAPI)

Of course, you can also use unpkg.

Usage

Global Registration

import { createApp } from 'vue'
import { install as VueMonacoEditorPlugin } from '@guolao/vue-monaco-editor'

const app = createApp(App)
app.use(VueMonacoEditorPlugin, {
  paths: {
    // You can change the CDN config to load other versions
    vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs'
  },
})

Local Registration

// main.ts
import { loader } from '@guolao/vue-monaco-editor'
loader.config({
  paths: {
    vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs',
  },
})

// editor.vue
import { VueMonacoEditor } from '@guolao/vue-monaco-editor'
export default {
  components: { VueMonacoEditor },
}

And then, use it.

Editor

<template>
  <vue-monaco-editor
    v-model:value="code"
    theme="vs-dark"
    :options="MONACO_EDITOR_OPTIONS"
    @mount="handleMount"
  />
</template>

<script lang="ts" setup>
import { ref, shallowRef } from 'vue'

const MONACO_EDITOR_OPTIONS = {
  automaticLayout: true,
  formatOnType: true,
  formatOnPaste: true,
}

const code = ref('// some code...')
const editor = shallowRef()
const handleMount = editorInstance => (editor.value = editorInstance)

// your action
function formatCode() {
  editor.value?.getAction('editor.action.formatDocument').run()
}
</script>

Diff Editor

<template>
  <vue-monaco-diff-editor
    theme="vs-dark"
    original="// the original code"
    modified="// the modified code"
    language="javascript"
    :options="OPTIONS"
    @mount="handleMount"
  />
</template>

<script lang="ts" setup>
import { ref, shallowRef } from 'vue'

const OPTIONS = {
  automaticLayout: true,
  formatOnType: true,
  formatOnPaste: true,
  readOnly: true,
}

const diffEditor = shallowRef()
const handleMount = diffEditorInstance => (diffEditor.value = diffEditorInstance)

// get the original value
function getOriginalValue() {
  return diffEditor.value.getOriginalEditor().getValue()
}

// get the modified value
function getModifiedValue() {
  return diffEditor.value.getModifiedEditor().getValue()
}
</script>

Props & Events & slots

Editor

NameTypeDefaultDescriptionremark
valuestringvalue of the current model, can use v-model:valuev-model:value
languagestringall language of the current modellanguages supported by monaco-editor, view here
pathstringpath to the current model
defaultValuestringdefault value of the current model
defaultLanguagestringdefault language of the current modellanguages supported by monaco-editor view here
defaultPathstringdefault path of the current modelmonaco.editor.createModel(..., ..., monaco.Uri.parse(defaultPath))
themevs | vs-darkvsthe theme for the monaco editor.
linenumbernumber of lines to jump to
optionsobject{}IStandaloneEditorConstructionOptions
overrideServicesobject{}IEditorOverrideServices
saveViewStatebooleantruesave the view state of the model (scroll position, etc.) after model changesa unique path needs to be configured for each model
widthnumber | string100%container width
heightnumber | string100%container height
classNamestringinner container class name
@beforeMount(monaco: Monaco) => voidexecute before the editor instance is created (don't use @before-mount in vue2, detail)
@mount(editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => voidexecute after the editor instance has been created
@change(value: string \| undefined, event: monaco.editor.IModelContentChangedEvent) => voidexecute when the changed value change
@validate(markers: monaco.editor.IMarker[]) => voidexecute when a syntax error occursmonaco-editor supports syntax-checked languages view here
#defaultslot'loading...'loading statuswhen loading files from CDN, displaying the loading status will be more friendly
#failureslot'load failed'failure statusexample: CDN network error

Diff Editor

NameTypeDefaultDescription
originalstringThe original source value (left editor)
modifiedstringThe modified source value (right editor)
languagestringLanguage for the both models - original and modified (all languages that are supported by monaco-editor)
originalLanguagestringThis prop gives you the opportunity to specify the language of the original source separately, otherwise, it will get the value of the language property.
modifiedLanguagestringThis prop gives you the opportunity to specify the language of the modified source separately, otherwise, it will get the value of language property.
originalModelPathstringPath for the "original" model. Will be passed as a third argument to .createModel method - monaco.editor.createModel(..., ..., monaco.Uri.parse(originalModelPath))
modifiedModelPathstringPath for the "modified" model. Will be passed as a third argument to .createModel method - monaco.editor.createModel(..., ..., monaco.Uri.parse(modifiedModelPath))
themevs | vs-dark | stringvs (vs theme equals light theme)The theme for the monaco editor. Define new themes by monaco.editor.defineTheme.
optionsobject{}IStandaloneDiffEditorConstructionOptions
widthnumber | string100%Container width
heightnumber | string100%Container height
classNamestringInner container class name
@beforeMount(monaco: Monaco) => voidExecute before the editor instance is created (don't use @before-mount in vue2, detail)
@mount(editor: monaco.editor.IStandaloneDiffEditor, monaco: Monaco) => voidExecute after the editor instance has been created
#defaultslot'loading...'Loading status
#failureslot'load failed'Failure status

Hooks

useMonaco use @monaco-editor/loader to load monaco-editor from the CDN.

<template>
  <div ref="containerRef"></div>
</template>

<script lang="ts" setup>
import { ref, onUnmounted, watchEffect, nextTick } from 'vue'
import { useMonaco } from '@guolao/vue-monaco-editor'

const containerRef = ref()
const { monacoRef, unload } = useMonaco()

// watch once
const stop = watchEffect(() => {
  if (monacoRef.value && containerRef.value) {
    nextTick(() => stop())
    monacoRef.value.editor.create(containerRef.value, { ... })
  }
})

/*
  When the component will be unmount,
  If the monaco instance is not successfully loaded,
  You need to manually unload.
*/
onUnmounted(() => !monacoRef.value && unload())
</script>

CDN

vue-monaco-editor use @monaco-editor/loader to load the monaco-editor from the CDN(the loading process of loader is asynchronous).

The configuration of loader is global, only to be configured once.

import { createApp } from 'vue'
import { install as VueMonacoEditorPlugin } from '@guolao/vue-monaco-editor'

const app = createApp(App)
app.use(VueMonacoEditorPlugin, {
  paths: {
    // You can change the CDN config to load other versions
    vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs'
  },
})
import { loader } from "@guolao/vue-monaco-editor"

// loaded from CDN
loader.config({
  paths: {
    vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs'
  },
})

// configurable for different languages
loader.config({ "vs/nls": { availableLanguages: { "*": "de" } } })

// or
loader.config({
  paths: {
    vs: "...",
  },
  "vs/nls" : {
    availableLanguages: {
      "*": "de",
    },
  },
})

NPM Package

If you still want to import monaco-editor files from node_modules and bundle them into your code (without using remote loading), you will need to use a bundling tool.

import * as monaco from "monaco-editor"
import { loader } from "@guolao/vue-monaco-editor"

// loaded monaco-editor from `node_modules`
loader.config({ monaco })

Vite

If you are using vite, you need to do this (see #1791 (comment) for details).

import { loader } from "@guolao/vue-monaco-editor"

import * as monaco from "monaco-editor"
import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker"
import jsonWorker from "monaco-editor/esm/vs/language/json/json.worker?worker"
import cssWorker from "monaco-editor/esm/vs/language/css/css.worker?worker"
import htmlWorker from "monaco-editor/esm/vs/language/html/html.worker?worker"
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker"

self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === "json") {
      return new jsonWorker()
    }
    if (label === "css" || label === "scss" || label === "less") {
      return new cssWorker()
    }
    if (label === "html" || label === "handlebars" || label === "razor") {
      return new htmlWorker()
    }
    if (label === "typescript" || label === "javascript") {
      return new tsWorker()
    }
    return new editorWorker()
  }
}

loader.config({ monaco })

Rollup

If you are using Rollup, you can use the community provided plugin rollup-plugin-monaco-editor.

Webpack

If you are using webpack, monaco-editor officially provides a webpack plugin called monaco-editor-webpack-plugin, which you can install and use.

Inspiration

MonacoVue is made possible thanks to the inspirations from the following projects:

License

MIT