如何将 Monaco 与 Vue.js 集成?

tes*_*r12 11 javascript vue.js

我创建了一个新的 vue 应用程序并运行npm install -s monaco-editor,然后我将 App.vue 更改为如下所示:

<template>
    <div id="app" style="width: 500px; height: 500px;">
        <div ref="editor" style="width: 500px; height: 500px;"></div>
  </div>
</template>

<script>
import * as monaco from 'monaco-editor';

export default {
  name: 'app',
  async mounted() {
    const el = this.$refs.editor;
    this.editor = monaco.editor.create(el, {
      value: "console.log('hello world');",
      language: 'javascript',
    });
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我在 JavaScript 控制台中看到以下内容:

Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/Microsoft/monaco-editor#faq simpleWorker.js:31
You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker 2 simpleWorker.js:33
Error: "Unexpected usage"
    loadForeignModule editorSimpleWorker.js:494
    _foreignProxy webWorker.js:54
languageFeatures.js:209
    _doValidate languageFeatures.js:209
Run Code Online (Sandbox Code Playgroud)

我试过搜索错误,但大多数线程似乎都专注于通过 file:/// 访问文件,而我没有这样做(我正在访问节点网络服务器)。

此外,除非明确指定高度,否则编辑器不会正确呈现 - 我认为这不是预期的行为。

如何让 monaco-editor 在 Vue 中正常工作?如果可能,出于支持原因,我想避免使用非官方的第三方包装器,例如https://github.com/egoist/vue-monaco

Node/Vue 新手,所以请善待!

Ale*_*man 6

webpack尝试在 webpack 配置中指定 monaco插件:

const monacoWebpackPlugin = require('monaco-editor/webpack')

...

plugins: [
  new monacoWebpackPlugin()
]
Run Code Online (Sandbox Code Playgroud)

或者安装monaco-editor-webpack-plugin并尝试使用它:

const monacoWebpackPlugin = require('monaco-editor-webpack-plugin')

...

plugins: [
  new monacoWebpackPlugin()
]
Run Code Online (Sandbox Code Playgroud)

至于heightwidth,您可以监听窗口大小调整并调用editor.layout(),也可以计算容器大小并将大小传递给方法editor.layout()( 1)

或者您可以尝试类似线程中其他发布的答案中的一些内容,例如:

<div ref="editor" class="monaco-editor"></div>
Run Code Online (Sandbox Code Playgroud)
.monaco-editor {
  height: 100vh;
  overflow: hidden;
}

body {
  margin: 0;
  padding: 0;
}

Run Code Online (Sandbox Code Playgroud)

或者是这样的:

.monaco-editor {
  position: absolute; 
  left: 0; 
  top: 0;
  width: 100%; 
  height: 100%; 
  max-height: 100% !important;
  margin: 0; 
  padding: 0;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)


ruo*_* li 4

摩纳哥默认访问工人file://,但它不能在网络上工作。

您应该http://通过手动设置 MonacoEnviorment 或使用Monaco Webpack Plugin来替换它。

参考官方文档