Giter Club home page Giter Club logo

monaco-vue's Introduction

monaco-vue

🎉 version v1 support vue 2&3 now ✌

Use monaco-editor loaded from CDN in Vue 2&3, no need to configure plugins in webpack (or rollup, vite) and other packaging tools.

gitHub license npm version

English | 简体中文

View Demo.

If you wanna use monaco-editor as an NPM Package, loading monaco-editor files from node_modules and bundling them into your code, you still need to use the plugin for the packaging tool.

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

Of course, you can also use unpkg.

Usage

Register the component.

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

const app = createApp(App)
app.use(VueMonacoEditorPlugin, {
  paths: {
    // The recommended CDN config
    vs: 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs'
  },
})

// You can also:
// main.ts
import { loader } from '@guolao/vue-monaco-editor'
loader.config({
  paths: {
    vs: 'https://cdn.jsdelivr.net/npm/[email protected]/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 editorRef = shallowRef()
const handleMount = editor => (editorRef.value = editor)

// your action
function formatCode() {
  editorRef.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 diffEditorRef = shallowRef()
const handleMount = diffEditor => (diffEditorRef.value = diffEditor)

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

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

Props & Events & slots

Editor

Name Type Default Description remark
value string value of the current model, can use v-model:value v-model:value
language string all language of the current model languages supported by monaco-editor, view here
path string path to the current model
defaultValue string default value of the current model
defaultLanguage string default language of the current model languages supported by monaco-editor view here
defaultPath string default path of the current model monaco.editor.createModel(..., ..., monaco.Uri.parse(defaultPath))
theme vs | vs-dark vs the theme for the monaco editor.
line number number of lines to jump to
options object {} IStandaloneEditorConstructionOptions
overrideServices object {} IEditorOverrideServices
saveViewState boolean true save the view state of the model (scroll position, etc.) after model changes a unique path needs to be configured for each model
width number | string 100% container width
height number | string 100% container height
className string inner container class name
@beforeMount (monaco: Monaco) => void execute before the editor instance is created (don't use @before-mount in vue2, detail)
@mount (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => void execute after the editor instance has been created
@change (value: string | undefined, event: monaco.editor.IModelContentChangedEvent) => void execute when the changed value change
@validate (markers: monaco.editor.IMarker[]) => void execute when a syntax error occurs monaco-editor supports syntax-checked languages view here
#default slot 'loading...' loading status when loading files from CDN, displaying the loading status will be more friendly
#failure slot 'load failed' failure status example: CDN network error

Diff Editor

Name Type Default Description
original string The original source value (left editor)
modified string The modified source value (right editor)
language string Language for the both models - original and modified (all languages that are supported by monaco-editor)
originalLanguage string This prop gives you the opportunity to specify the language of the original source separately, otherwise, it will get the value of the language property.
modifiedLanguage string This prop gives you the opportunity to specify the language of the modified source separately, otherwise, it will get the value of language property.
originalModelPath string Path for the "original" model. Will be passed as a third argument to .createModel method - monaco.editor.createModel(..., ..., monaco.Uri.parse(originalModelPath))
modifiedModelPath string Path for the "modified" model. Will be passed as a third argument to .createModel method - monaco.editor.createModel(..., ..., monaco.Uri.parse(modifiedModelPath))
theme vs | vs-dark | string vs (vs theme equals light theme) The theme for the monaco editor. Define new themes by monaco.editor.defineTheme.
options object {} IStandaloneDiffEditorConstructionOptions
width number | string 100% Container width
height number | string 100% Container height
className string Inner container class name
@beforeMount (monaco: Monaco) => void Execute before the editor instance is created (don't use @before-mount in vue2, detail)
@mount (editor: monaco.editor.IStandaloneDiffEditor, monaco: Monaco) => void Execute after the editor instance has been created
#default slot 'loading...' Loading status
#failure slot '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: {
    // The recommended CDN config
    vs: 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs'
  },
})
import { loader } from "@guolao/vue-monaco-editor"

// loaded from CDN
loader.config({
  paths: {
    vs: 'https://cdn.jsdelivr.net/npm/[email protected]/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 wanna use monaco-editor as an NPM Package, loading monaco-editor files from node_modules and bundling them into your code, you still need to use the plugin for the packaging 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, the official monaco-editor 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

monaco-vue's People

Contributors

cat1007 avatar imguolao avatar jeanjpnm avatar lehaolin avatar oluceps avatar qq1037305420 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

monaco-vue's Issues

Need vue2 example

I use in vue2, but was an error
My code :

<template>
  <div style="height: 500px">
    <vue-monaco-editor v-model="code" theme="vs-dark" :options="MONACO_EDITOR_OPTIONS" @mounted="handleMount" />
    <button @click="formatCode">Format Code</button>
  </div>
</template>
<script>
import { VueMonacoEditor } from "@guolao/vue-monaco-editor";

export default {
  name: "monaco",
  components: { VueMonacoEditor },
  data() {
    return {
      code: "// some code...",
      MONACO_EDITOR_OPTIONS: {
        automaticLayout: true,
        formatOnType: true,
        formatOnPaste: true,
      },
      editorRef: "",
    };
  },
  methods: {
    handleMount(editor) {
      this.editorRef = editor;
    },
    formatCode() {
      if (this.editorRef) {
        this.editorRef.getAction("editor.action.formatDocument").run();
      }
    },
  },
};
</script>
<style>
button {
  margin-top: 10px;
}
</style>

error
image

version :

"@guolao/vue-monaco-editor": "^1.5.1",
 "@vue/composition-api": "^1.7.1",
 "vue": "^2.6.14",

why not lien prop does not work

<vue-monaco-editor
v-show="showEdit"
:line="item.line"
v-model:value="mainStore.$state.raw_data"
theme="vs-dark"
:options="MONACO_EDITOR_OPTIONS"
@mount="handleMount"
height="200px"
/>

Modify monaco before loader.config({ monaco })

Hello,

I am trying to enable SchemaRequest of the JSON language and tried this :

import { install as VueMonacoEditorPlugin, loader } from '@guolao/vue-monaco-editor'
import * as monaco from 'monaco-editor'

import { type UserModule } from '~/types'

// Setup Monaco Editor
// https://www.npmjs.com/package/@guolao/vue-monaco-editor
export const install: UserModule = ({ app }) => {
  monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
    ...monaco.languages.json.jsonDefaults.diagnosticsOptions,
    allowComments: true,
    enableSchemaRequest: true,
  })

  loader.config({ monaco })

  app.use(VueMonacoEditorPlugin, {})
}

But this don't seems to work, what is the correct way to do it ?

Thanks

Not working with 'warn' messages and some configurations

[Vue warn]: Failed to resolve component: vue-monaco-editor If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <App>

When I refer to and implement 'https://github.com/imguolao/monaco-vue#usage' ', the following message pops up.

And 'vue-monaco-editor' is not displayed on the screen.

But if you refer to 'https://github.com/imguolao/monaco-vue#hooks ' here, it works. I want to get rid of the 'warn' message, and I want to make it work as it says here at https://github.com/imguolao/monaco-vue#hooks' .

/* my package.json */
{
  "name": "vue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "local": "vue-cli-service serve --mode localhost --port 8080",
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^3.2.13",
    "monaco-editor": "0.41.0",
    "@guolao/vue-monaco-editor": "1.1.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  ]
}

UMD

Any UMD example?

It is not possible to load a custom monaco instance with `await import`

I was trying to use the version of monaco-editor from my node_modules folder and bundle it using vite to only import the languages that the component uses, however, I couldn't find a way to use the dynamically imported monaco instance with the Editor component. ``:

monaco.ts

import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker";
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker";

// based on
// https://github.com/vitejs/vite/discussions/1791#discussioncomment-321046
// the other workers were removed since the editor
// only needs the typescript language server
self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === "typescript" || label === "javascript") {
      return new tsWorker();
    }
    return new editorWorker();
  },
};

export * from "monaco-editor";
<template>
  <Editor v-model:value="valueRef"></Editor>
</template>

<script setup>
import Editor from "@guolao/vue-monaco-editor";
import { onMounted, ref } from "vue";

const valueRef = ref("");

onMounted(async () => {
  const monaco = await import("./monaco");

  // the editor already loaded its own monaco instance
  // so calling loader.config({monaco}) won't work
});
</script>

bug: the monaco editor is loaded during SSR

I'm currently using this editor in a vitepress project, where I have a custom component that uses the Editor internally.
In the vitepress docs, it is indicated to wrap components that depend on browser APIs with <Clientonly>, however, this does not work well in this scenario because I need to render the contents of my vue component with the loading placeholder during ssr.

One way to solve this issue would be to update the useMonaco function to call loader.init within the onMounted callback.

Update monaco-editor

The monaco-editor dependency is in version 0.45.0 and the package in 0.43.0.

Thanks.

0.41.0 The input prompt is not displayed.

I found that the code prompt of version 36 is normal. If you upgrade to 41, the code prompt will not exist.. Excuse me, can it be repaired?

app.use(VueMonacoEditorPlugin, {
  paths: {
    // The default CDN config
    vs: 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs'
  },
})
image

在vue 2.6.14使用时报错无法使用

vue版本 2.6.14,已安装@vue/composition-api,在单页引入后报错

Module parse failed: Unexpected token (49:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders      
|   const unload = () => monacoLoader.cancel();
|   monacoLoader.then(monacoInstance => monacoRef.value = monacoInstance).catch(error => {
>     if (error?.type !== "cancelation") {
|       console.error("Monaco initialization error:", error);
|     }

Add error handling when CDN fails

I'm planning to use the editor in an environment where the web app comes from a local network and the internet is not always reliable or available. I need a way to react to failed initialization (CDN loading) of the editor.
Are there any hooks or mechanisms I can use to implement this right now?
Currently I only get a logged error

onMounted(() => {
// the instance has already been loaded
if (monacoRef.value) return
promise = loader.init()
promise
.then(monacoInstance => (monacoRef.value = monacoInstance))
.catch(error => {
if (error?.type !== 'cancelation') {
console.error('Monaco initialization error:', error)
}
})
})
but haven't found a way to react to it properly.

I'm planning to fall back to a simple textarea. Maybe this fallback mode could also be a built-in feature of this plugin?

textModel.ts:73 Uncaught (in promise) TypeError: $.create is not a function

<el-table :data="columnsConfig" border style="width: 100%">
            <el-table-column prop="label" label="列名">
              <template #default="scope">
                <el-input v-model="scope.row.label" placeholder="添加列名"></el-input>
              </template>
            </el-table-column>

            <el-table-column prop="format" label="Format" width="700">
              <template #default="scope">
                <div style="height: 200px">
                  <vue-monaco-editor
                      v-model:value="scope.row.format"
                      theme="vs-dark"
                      language="javascript"
                      :options="MONACO_EDITOR_OPTIONS"
                      @mount="handleMount"
                      @input="updateFormat(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="label" label="渲染颜色">
              <template #default="scope">
                <el-color-picker v-model="scope.row.color" size="large"/>
              </template>
            </el-table-column>
            <el-table-column>
              <template #header>
                <el-button icon="Plus" @click="addColumn" type="success">添加列</el-button>
              </template>
              <template #default="scope">
                <el-button icon="Minus" @click="removeColumn(scope.$index)" type="warning">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
                   
<script setup lang="ts">
import {computed, reactive, ref, shallowRef, watch} from "vue";
import type {CheckboxValueType, FormInstance, FormRules} from "element-plus";
import {ElMessage} from "element-plus";
import SubPage from "@/common/SubPage.vue";
import {VueMonacoEditor} from '@guolao/vue-monaco-editor'
const MONACO_EDITOR_OPTIONS = {
  automaticLayout: true,
  formatOnType: true,
  formatOnPaste: true,
}

const editorRef = shallowRef()
const handleMount = editor => (editorRef.value = editor)

const updateFormat = (row) => {
  if (row.format) {
    // Assume format should be an array like ["date", "php:Y-m-d"]
    row.format = row.format.includes(',') ? row.format.split(',') : [row.format];
  }
};

how to add a custom language for this module?

I use this module via CDN, but now I want to add a custom language, similar to what is described in the documentation at https://microsoft.github.io/monaco-editor/monarch.html. The registration method I usually find online is

monaco.languages.register({ id: 'mylang' });. 

How should I register a custom language in this module?
Now I use Like:
我现在使用CDN的方式接入vue-monaco-editor,使用vue2+composition-api的方式接入,接入代码如下,现在我想加入一种自定义语言(NGINX)像 #39 一样,但我看都是使用

monaco.languages.register({ id: 'mylang' });.

的方式找到对象并注册语法,在我这种使用方式中应该如何向对象中注册新的语法呢?

import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'
Vue.use(VueCompositionAPI)
import { createApp } from '@vue/composition-api';
import App from '../../../../App.vue'
import { install as VueMonacoEditorPlugin, loader } from '@guolao/vue-monaco-editor'
const app = createApp(App)
app.use(VueMonacoEditorPlugin)
loader.config({
  "vs/nls": {
    availableLanguages: {
      "*": "zh-cn",
    }
  },
  "paths": {
    vs: "http://localhost:8081/monaco-editor/min/vs"
  }
})
<vue-monaco-editor style="height: 250px;width: 100%;border-radius: 2px;border: 1px solid #d7dae2;"
                  v-model:value="test"/>

Error Using Latest Monaco Package

There's a conflicting dependency when trying to use the latest monaco editor (0.37.1) with vue-monaco-editor where the requirements is 0.35.0 (see below). Please update the package to accept future versions. Thanks!

npm ERR! While resolving: @guolao/[email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/monaco-editor
npm ERR!   monaco-editor@"^0.37.1" from the root project
npm ERR!   peer monaco-editor@">= 0.21.0 < 1" from @monaco-editor/[email protected]
npm ERR!   node_modules/@monaco-editor/loader
npm ERR!     @monaco-editor/loader@"^1.3.2" from @guolao/[email protected]
npm ERR!     node_modules/@guolao/vue-monaco-editor
npm ERR!       @guolao/vue-monaco-editor@"^1.1.3" from the root project
npm ERR!   1 more (monaco-editor-webpack-plugin)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer monaco-editor@"^0.35.0" from @guolao/[email protected]
npm ERR! node_modules/@guolao/vue-monaco-editor
npm ERR!   @guolao/vue-monaco-editor@"^1.1.3" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/monaco-editor
npm ERR!   peer monaco-editor@"^0.35.0" from @guolao/[email protected]
npm ERR!   node_modules/@guolao/vue-monaco-editor
npm ERR!     @guolao/vue-monaco-editor@"^1.1.3" from the root project

pnpm only?

Howdy! You mention installing this using various package managers but then have npx only-allow pnpm as a preinstall command. Is that intentional?

I use [email protected] but i don't install by npm.

Could not resolve dependency:
@guolao/vue-monaco-editor@"*" from the root project

Conflicting peer dependency: [email protected]
node_modules/vue
peer vue@">= 2.5 < 2.7" from @vue/[email protected]
node_modules/@vue/composition-api
peerOptional @vue/composition-api@"^1.7.1" from @guolao/[email protected]
node_modules/@guolao/vue-monaco-editor
@guolao/vue-monaco-editor@"*" from the root project

Fix the upstream dependency conflict, or retry
this command with --force or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

How to get Range from Editor or Highlight Lines?

So basically I want to highlight some lines of code ( for showing code coverage) and I want to use createDecorationsCollection function but here I am facing issue with "new monaco.Range" as I am not able get monaco instance, I am sorry as I am new to VueJs and figuring out things. I just want to make this work. Any help is appreciated.

below is the code I want to fix -->

var decorations = editorRef.createDecorationsCollection([
{
range: new monaco.Range(7, 1, 9, 1), // (startLineNumber, startColumn, endLineNumber, endColumn)
options: {
className: "bg-emerald-500",
isWholeLine: true },
},
]);

Missing functions inside useMonaco

Screenshot 2024-04-11 at 14 54 40

I console.log the editor property in useMonaco and some functions relating to model handling like setModel,... are not there. Any guess?

自定义建议提示项问题

怎么在json语言editor设置的设置下,实现对于输入双引号就出现自定义建议提示语的效果。目前在provideCompletionItems的方法中,输入""根本不会触发

`build.rollupOptions.output` in `vite.config.ts` is not working

After vite build, I found files with filename similar to editor.worker-[hash].js in the /dist/assets/ directory.

The config prop build.rollupOptions.output in vite.config.ts is not working. How to config the output directory for this component's worker files?


在 Vite 中按需使用组件时,我使用了文档提供的 loader.config({ monaco }) 方式引入。在执行编译后,我在 /dist/assets/ 目录中找到了文件名类似 editor.worker-[hash].js 的文件。

根据实际项目的需要,我事先在 Vite 的配置文件中修改了 build.rollupOptions.output 属性,自定义配置了编译生成文件的目录(比如把编译生成的资源文件目录从 /dist/assets/ 修改为 /dist/a/b/c/)。但是这个组件的 editor.worker-[hash].js 等文件,似乎并没有遵循 Vite 的相关配置,而是固定为 /dist/assets/ 的路径。

由于特殊的生产环境需求,目前我只能改用 CDN 方案来解决这个问题:在 public 静态文件目录中创建一个 [email protected] 的目录用于存放 [email protected]/min/vs 的内容,然后使用 CDN 方式引入。

{ vs: `${BASE_URL}[email protected]` }

这种方式应该是注册了全局组件,不优雅。不知是否能提供遵循 Vite 配置的方案?

path、value、language 同时配置时出现的bug

源码中的 pathvaluelanguage 使用了3个不同的 watch 导致更新时存在回调执行顺序问题,editorRef.value!.getModel()getOrCreateModel 调用的顺序存在问题!

    // path
    watch(
      () => props.path,
      (newPath, oldPath) => {
        const model = getOrCreateModel(
          monacoRef.value!,
          props.value || props.defaultValue || '',
          props.language || props.defaultLanguage || '',
          newPath || props.defaultPath || '',
        )

        if (model !== editorRef.value!.getModel()) {
          props.saveViewState && viewStates.set(oldPath, editorRef.value!.saveViewState())
          editorRef.value!.setModel(model)
          props.saveViewState && editorRef.value!.restoreViewState(viewStates.get(newPath)!)
        }
      },
    )

    // value
    watch(
      () => props.value,
      newValue => {
        if (editorRef.value && editorRef.value.getValue() !== newValue) {
          editorRef.value.setValue(newValue!)
        }
      },
    )

    // language
    watch(
      () => props.language,
      language =>
        isEditorReady.value && monacoRef.value!.editor.setModelLanguage(editorRef.value!.getModel()!, language!),
    )

应该使用

watch([() => props.path, () => props.value, () => props.language], ([newPath, newValue, newLanguage]) => {
    // 统一执行回调逻辑,控制好 editorRef.value!.getModel()与 getOrCreateModel 的调用顺序存
})

其它 props 的 watch 不知道有没有类似问题,需要检查

Vue 2 support?

Hi, I was trying to add this component to my Vue 2 project and it requires Vue 3. Are you planning to add Vue 2 support?

[FAQ] 自定义语言和主题 - Custom languages and themes

不能直接导入monaco-editor注册语言,需要使用mount事件的第二个参数提供的monaco对象注册语言

<template>
  <vue-monaco-editor language="mylang" theme="mylang-theme" :options="options" @mount="ready" />
</template>

<script lang="ts" setup>
import type { editor } from 'monaco-editor/esm/vs/editor/editor.api'

const options: editor.IStandaloneEditorConstructionOptions = {
  contextmenu: false,
  minimap: {
    enabled: false
  },
  smoothScrolling: true,
  cursorBlinking: 'expand',
  scrollbar: {
    vertical: 'hidden',
    horizontal: 'hidden'
  },
  overviewRulerLanes: 0,
  lineNumbers: 'off'
}

function ready(_e: unknown, monaco: typeof import('monaco-editor')) {
  // 防止重复注册
  if (
    !monaco.languages
      .getLanguages()
      .map((lang) => lang.id)
      .includes('mylang')
  ) {
    monaco.languages.register({
      id: 'mylang'
    })
    monaco.languages.setMonarchTokensProvider('mylang', {
      tokenizer: {
        root: [
          [/^\/[a-z:]/, { token: 'keyword' }],
          [/test/, { token: 'keyword' }]
        ]
      }
    })
    monaco.editor.defineTheme('mylang-theme', {
      base: 'vs',
      inherit: true,
      rules: [{ token: 'keyword', foreground: '#000ed1', fontStyle: 'bold' }],
      colors: {}
    })
  }
}
</script>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.