Git Product home page Git Product logo

vue-monaco's Introduction

vue-monaco

NPM version NPM downloads CircleCI donate

Monaco Editor is the code editor that powers VS Code, now it's available as a Vue component <MonacoEditor> thanks to this project.

Install

npm install vue-monaco

Or

yarn add vue-monaco

Usage

Use ESM version with webpack

Use monaco-editor-webpack-plugin:

// webpack.config.js
const MonacoEditorPlugin = require('monaco-editor-webpack-plugin')

module.exports = {
  plugins: [
    new MonacoEditorPlugin({
      // https://github.com/Microsoft/monaco-editor-webpack-plugin#options
      // Include a subset of languages support
      // Some language extensions like typescript are so huge that may impact build performance
      // e.g. Build full languages support with webpack 4.0 takes over 80 seconds
      // Languages are loaded on demand at runtime
      languages: ['javascript', 'css', 'html', 'typescript']
    })
  ]
}

Then use the component:

<template>
  <MonacoEditor class="editor" v-model="code" language="javascript" />
</template>

<script>
import MonacoEditor from 'vue-monaco'

export default {
  components: {
    MonacoEditor
  },

  data() {
    return {
      code: 'const noop = () => {}'
    }
  }
}
</script>

<style>
.editor {
  width: 600px;
  height: 800px;
}
</style>

Use AMD version

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  </head>
  <body>
    <div id="app"></div>

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vue-monaco"></script>
    <script src="monaco-editor/min/vs/loader.js"></script>
    <script>
      require.config({ paths: { vs: 'monaco-editor/min/vs' } })

      new Vue({
        el: '#app',
        template: `
          <monaco-editor
            style="width:800px;height:600px;border:1px solid grey"
            v-model="code" 
            language="javascript" 
            :amdRequire="amdRequire"
          />`,
        data: {
          code: 'const noop = () => {}'
        },
        methods: {
          amdRequire: require
        }
      })
    </script>
  </body>
</html>

When loading monaco-editor from a CDN, you need to change require.config to look like this:

require.config({ paths: { vs: 'http://www.mycdn.com/monaco-editor/min/vs' } })

// Before loading vs/editor/editor.main, define a global MonacoEnvironment that overwrites
// the default worker url location (used when creating WebWorkers). The problem here is that
// HTML5 does not allow cross-domain web workers, so we need to proxy the instantiation of
// a web worker through a same-domain script
window.MonacoEnvironment = {
  getWorkerUrl: function(workerId, label) {
    return `data:text/javascript;charset=utf-8,${encodeURIComponent(`
        self.MonacoEnvironment = {
          baseUrl: 'http://www.mycdn.com/monaco-editor/min/'
        };
        importScripts('http://www.mycdn.com/monaco-editor/min/vs/base/worker/workerMain.js');`)}`
  }
}

Props

  • options: The second argument of monaco.editor.create.
  • value: A shortcut to set options.value.
  • theme: A shortcut to set options.theme.
  • language: A shortcut to set options.language.
  • amdRequire: Load monaco-editor using given amd-style require function.
  • diffEditor: boolean Indicate that this is a DiffEditor, false by default.

Component Events

editorWillMount

Called before mounting the editor.

editorDidMount

Called when the editor is mounted.

change

Editor value is updated.

Editor Events

You can listen to the editor events directly like this:

<template>
  <MonacoEditor v-model="code" @editorDidMount="editorDidMount" />
</template>

<script>
export default {
  methods: {
    editorDidMount(editor) {
      // Listen to `scroll` event
      editor.onDidScrollChange(e => {
        console.log(e)
      })
    }
  },

  data() {
    return {
      code: '...'
    }
  }
}
</script>

Refer to this page for all editor events.

Methods

Use ref to interact with the MonacoEditor component in order to access methods: <MonacoEditor ref="editor" />, then this.$refs.editor.getEditor() will be available.

Use the DiffEditor

Use diffEditor prop to indicate that this is a DiffEditor, use original prop to set the content for the original editor, use value prop to set the content for the modified editor.

<MonacoEditor
  language="javascript"
  :diffEditor="true"
  :value="code"
  :original="originalCode"
/>

In this case, the component's getEditor() returns the IStandaloneDiffEditor instance, while you can use getModifiedEditor() to get the modified editor which is an IStandaloneCodeEditor instance.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

Author

vue-monaco © egoist, Released under the MIT License.
Authored and maintained by egoist with help from contributors (list).

Website · GitHub @egoist · Twitter @_egoistlily

vue-monaco's People

Contributors

andron58 avatar backlighting-neo avatar cdrini avatar dependabot-preview[bot] avatar egoist avatar matsev avatar meanmail avatar peterhpchen avatar prodigy99 avatar ramiy avatar saman 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-monaco's Issues

How to customize the editor before create

Hi, I want to register a customized language like https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages.

But whether I got the editor instance via editorDidMount or this.$refs.editor.getEditor(), the editor instance did not contain languages, defineTheme and so on.

I want to execute the following code.

    // Register a new language
    monaco.languages.register({ id: 'bind9' })
    // Register a tokens provider for the language
    monaco.languages.setMonarchTokensProvider('bind9', {
      tokenizer: {
        root: [
          [/IN/, 'record-className'],
          [/(SOA|NS|MX|TXT|A|AAAA|CNAME)/, 'record-type'],
        ],
      },
    })
    // Define a new theme that contains only rules that match this language
    monaco.editor.defineTheme('bind9Theme', {
      base: 'vs',
      inherit: false,
      rules: [
        { token: 'record-className', foreground: '808080' },
        { token: 'record-type', foreground: 'ff0000', fontStyle: 'bold' },
      ],
    })

I also reviewed the readme of https://github.com/Microsoft/monaco-editor-webpack-plugin, but still got nothing help.

TypeError: this.require is not a function

write demo according to the readme , get exception:

TypeError: this.require is not a function
    at VueComponent.mounted (vue-monaco.common.js?70e3:75)
    at callHook (vue.esm.js?efeb:2921)
    at Object.insert (vue.esm.js?efeb:4158)
    at invokeInsertHook (vue.esm.js?efeb:5960)
    at Vue.patch [as __patch__] (vue.esm.js?efeb:6179)
    at Vue._update (vue.esm.js?efeb:2660)
    at Vue.updateComponent (vue.esm.js?efeb:2788)
    at Watcher.get (vue.esm.js?efeb:3142)
    at new Watcher (vue.esm.js?efeb:3131)
    at mountComponent (vue.esm.js?efeb:2795)

demo code:

  1. App.vue
<script src="../node_modules/monaco-editor-core/min/vs/loader.js"></script>
<script>
 require.config({
   paths: {
     vs: '../node_modules/monaco-editor-core/min/vs'
   }
 })
</script>

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

2.helloworld.vue

<template>
  <monaco-editor
    class="editor"
    v-model="code"
    language="javascript">
  </monaco-editor>
</template>

<script>
import MonacoEditor from 'vue-monaco'

export default {
  components: {
    MonacoEditor
  },

  data () {
    return {
      code: 'const noop = () => {}'
    }
  }
}
</script>

<style>
  .editor {
    width: 600px;
    height: 800px;
  }
</style>

How to setup json schema?

I'm trying to use my custom JSON schema in editor content but it doesn't work.

editorWillMount(monaco) {
        monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
          schemas: [
            {
              schema: schema  ///  from import
            }
          ]
        });
      },

What am I missing?

diffEditor的original显示值不变化

用v-bind:original=”originalValue“,更改originalValue值之后,通过断点发现original的值是变化的,但是在页面上编辑框左侧的值,并不会发生变化,还是原来的

use v-bind:original=”originalValue“, and when i change the value of originalValue, i found that the value of original has already changed, but on the webpage, the value on the left of editor area still remains, how can i change the value shown on the webpage

image

How exactly do you pass in a require property for electron

I'm trying to use this in electron. I've downloaded the Monaco sample project (https://github.com/Microsoft/monaco-editor-samples/tree/master/electron-amd) and that runs fine in electron - but I'm at a loss how to make your component work in electron.

I understand I can pass in a require property - but I'm not exactly clear how to do that.

I assume I use it like this:

<template>
  <monaco-editor
    class="editor"
    v-model="code"
    require="???????"
    language="javascript">
  </monaco-editor>
</template>

Do I construct my own amdRequire and pass it in?

Do i do something like :require=COMPUTED_PROPERTY

Any chance you know how to make this work in electron? I've tried a few routes and got confused.

Sample Code from Microsoft

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Monaco Editor!</title>
	</head>
	<body>
		<h1>Monaco Editor in Electron!</h1>
		<div id="container" style="width:500px;height:300px;border:1px solid #ccc"></div>
	</body>

	<script>
		// Monaco uses a custom amd loader that overrides node's require.
		// Keep a reference to node's require so we can restore it after executing the amd loader file.
		var nodeRequire = global.require;
	</script>
	<script src="../node_modules/monaco-editor/min/vs/loader.js"></script>
	<script>
		// Save Monaco's amd require and restore Node's require
		var amdRequire = global.require;
		global.require = nodeRequire;
	</script>

	<script>
		// require node modules before loader.js comes in
		var path = require('path');

		function uriFromPath(_path) {
			var pathName = path.resolve(_path).replace(/\\/g, '/');
			if (pathName.length > 0 && pathName.charAt(0) !== '/') {
				pathName = '/' + pathName;
			}
			return encodeURI('file://' + pathName);
		}

		amdRequire.config({
			baseUrl: uriFromPath(path.join(__dirname, '../node_modules/monaco-editor/min'))
		});

		// workaround monaco-css not understanding the environment
		self.module = undefined;

		// workaround monaco-typescript not understanding the environment
		self.process.browser = true;

		amdRequire(['vs/editor/editor.main'], function() {
			var editor = monaco.editor.create(document.getElementById('container'), {
				value: [
					'function x() {',
					'\tconsole.log("Hello world!");',
					'}'
				].join('\n'),
				language: 'javascript'
			});
		});
	</script>
</html>

how to create DiffEditor?

Issuehunt badges

Is it possible to create DiffEditor using this package? If yes can anybody provide pointers to that? thanks in advance.


IssueHunt Summary

[
<
i
m
g

s
r
c

'
h
t
t
p
s
:
/
/
a
v
a
t
a
r
s
2
.
g
i
t
h
u
b
u
s
e
r
c
o
n
t
e
n
t
.
c
o
m
/
u
/
8
7
8
4
7
1
2
?
v

4
'

a
l
t

'
e
g
o
i
s
t
'

w
i
d
t
h

2
4

h
e
i
g
h
t

2
4

e
g
o
i
s
t
]
(
h
t
t
p
s
:
/
/
i
s
s
u
e
h
u
n
t
.
i
o
/
u
/
e
g
o
i
s
t
)

h
a
s

b
e
e
n

r
e
w
a
r
d
e
d
.

Backers (Total: $100.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Setting language doesn't work

I'm having issues when I try to set the language of the editor as a prop... here's the code I'm using:

 <MonacoEditor
   v-if="view.currentTab === 'template'"
   theme="vs-dark"
  language="html"
  :value="request.template"
  :options="options"
  @change="onTemplateChange"
>

Everything works apart from setting a language as a prop. I've also tried setting it in the options data array but that didn't work either.

You can see my full code here where I'm using the Monaco Editor.

Toggling diffEditor is not working

I have the following code:

<MonacoEditor
              class="monaco-editor"
              language="powershell"
              theme="vs-dark"
              ref="monaco-editor"
              :value="value"
              :options="monacoOptions"
              @change="onChange"
              :original="originalValue"
              :diffEditor="showDiffEditor"
 />

Toggling showDiffEditor does not swap between the normal editor and the diff editor.

Is this expected to work?

Warnings & errors (+)

I'm getting some warnings and errors in console.

Warning: 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
Error: Unexpected usage
    at EditorSimpleWorkerImpl.BaseEditorSimpleWorker.loadForeignModule (editorSimpleWorker.js?ccf6:468)
    at eval (webWorker.js?af50:39)
Error: undefined:1 Uncaught SyntaxError: Unexpected token <

I'm using vue-CLI 3 generated base app with vue.config.js:

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
	configureWebpack: {
		plugins: [
			new MonacoWebpackPlugin({
				languages: ['javascript', 'css', 'html']
			})
		]
	}
}

What I'm doing wrong?

languageDefinitiones is undefined

image\

this is my 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', 'text']
      })
    ]
  }
}

Uncaught Error: Unexpected usage

errors.js?0f90:57 Uncaught Error: Unexpected usage

Error: Unexpected usage
at EditorSimpleWorkerImpl.BaseEditorSimpleWorker.loadForeignModule (editorSimpleWorker.js?8c76:468)
at eval (webWorker.js?a9b4:39)
at eval (errors.js?0f90:57)

Usage with nuxt

I'm just trying to use the editor with nuxt, but I couldn't figure out how to confgiure nuxt or vue-monaco properly to build. Is there any chance someone knows how to configure the component for nuxt?

using other languages plugins

I'm using vue-monaco together with the webpack plugin , and I want to add synthax checking for yaml. I found a monaco-yaml module for this, but I m a bit confused on how to use it together with vue & webpack. does anybody have done this (even for other languages) ?

How to format code?

I want to format code when mount the editor.

Actually shows like this:
image

But, I need this value starts formated.

I try to use editorDidMount
image

But the StandaloneEditor don't have getAction method to call format
image

How to add customized language?

I want to add my customized language, and I use the demo in Monaco Editor Playground. I bind the event editorWillMount, and use the monaco object to add customized language, but its highlight does not work.

And I also see this issue, he add languages in editorDidMount. I tried it, but it does not work either.

<template>
  <MonacoEditor class="editor" v-model="code" language="mySpecialLanguage" @editorWillMount="editorWillMount" />
</template>

<script>
import MonacoEditor from 'vue-monaco'

export default {
  components: {
    MonacoEditor
  },

  data() {
    return {
      code: '[Sun Mar 7 16:02:00 2004] [notice] Apache/1.3.29 (Unix) configured -- resuming normal operations'
    }
  },

  methods: {
    editorWillMount(monaco) {
      // Register a new language
      monaco.languages.register({ id: 'mySpecialLanguage' });

      // Register a tokens provider for the language
      monaco.languages.setMonarchTokensProvider('mySpecialLanguage', {
        tokenizer: {
          root: [
            [/\[error.*/, "custom-error"],
            [/\[notice.*/, "custom-notice"],
            [/\[info.*/, "custom-info"],
            [/\[[a-zA-Z 0-9:]+\]/, "custom-date"],
          ]
        }
      });
    }
  }
}
</script>

<style>
.editor {
  width: 600px;
  height: 800px;
}
</style>

Editors on page stuck at 5px height and width

Hi, thanks for the great vue component!.

I am trying to render multiple editors on the same page. However, when I load the page, all of the editors show up as a 5px black square. It's as if the editor is not yet finished loading before it is rendered.

If I add a v-if on the editors and toggle the v-if value, then it appears as expected.

Any thoughts as to why this may be happening? Spent awhile debugging it to no avail yet.

[Vue warn]: Error in mounted hook

configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
    }
    config.plugins.push(
      new MonocoEditorPlugin({ languages: ['javascript', 'css', 'html'] })
    )
  }
        <monaco-editor
            language="javascript"
            :options="editorOptions"
            :code="specCodes"
            :changeThrottle="500"
            @editorDidMount="editorMounted"
            @change="onCodeChange"
            theme="vs"
            width="900"
        >
        </monaco-editor>
[Vue warn]: Error in mounted hook: "TypeError: this.model.getOneIndent is not a function"

Cursor location jumps to end of line

We are using vue-monaco with the MonacoEditorPlugin. Attempting to click anywhere in the editor results in the cursor location jumping to the end of the line. Has anyone experienced this issue? Anyone know of a solution? Thanks in advance.

How to use suggestions ?

In a YAML code, i would like to display a list of strings when on a specific command "CTRL + whatever" or recognizing this character "(" for instance.
Do you know how ?

Error: Cannot find module 'vs/editor/contrib/anchorSelect/anchorSelect'

HI,

I have this error when I run npm run serve

ERROR  Error: Cannot find module 'vs/editor/contrib/anchorSelect/anchorSelect'
Require stack:
- C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\monaco-editor-webpack-plugin\out\index.js
- C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\vue.config.js
- C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\package.json
Error: Cannot find module 'vs/editor/contrib/anchorSelect/anchorSelect'
Require stack:
- C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\monaco-editor-webpack-plugin\out\index.js
- C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\vue.config.js
- C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\package.json
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:982:15)
    at Function.resolve (internal/modules/cjs/helpers.js:83:19)
    at resolveMonacoPath (C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\monaco-editor-webpack-plugin\out\index.js:34:28)
    at C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\monaco-editor-webpack-plugin\out\index.js:181:63
    at Array.map (<anonymous>)
    at createLoaderRules (C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\monaco-editor-webpack-plugin\out\index.js:181:43)
    at webpack (C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\webpack\lib\webpack.js:51:13)
    at serve (C:\Users\xxxxx\source\repos\grpc-tester\Qualifit.GrpcTester.UI\node_modules\@vue\cli-service\lib\commands\serve.js:163:22)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) 

My package.json:

"monaco-editor-webpack-plugin": "^3.0.0",
"vue-monaco": "^1.2.2",

My vue.config.js

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
module.exports = {
    publicPath: './',
    lintOnSave: false,
    runtimeCompiler: true,
    configureWebpack: {
        //Necessary to run npm link https://webpack.js.org/configuration/resolve/#resolve-symlinks
        resolve: {
            symlinks: false
        },           
    },
    chainWebpack: config => {
        config.plugin('monaco-editor').use(MonacoWebpackPlugin, [
            {
                // Languages are loaded on demand at runtime
                languages: ['json', 'javascript', 'html', 'xml'],
                features: ['!gotoSymbol']
            }
        ])
    },
.....  bla bla 

Thanks,
Costi

npm WARN [email protected] requires a peer of webpack@^4.5.0 but none was installed.

got warning

npm WARN [email protected] requires a peer of ajv@^5.0.0 but none was installed.
npm WARN [email protected] requires a peer of webpack@^4.5.0 but none was installed.
npm WARN [email protected] requires a peer of monaco-editor@^0.15.1 but none was installed.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

my dependencies in package.json

    "vue-monaco": "^1.0.0",
    "monaco-editor-webpack-plugin": "^1.7.0",

my devDependencies in package.json

    "webpack": "^2.6.1",
    "webpack-bundle-analyzer": "^2.2.1",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-hot-middleware": "^2.20.0",
    "webpack-merge": "^4.1.0"

the webpack I globally installed is 4.4.0

what webpack verison should i choose?

Question: How to highlight code lines?

I learn from README that we can get the editor instance through onEditorMount or getEditor(), then call APIs listed in https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandalonecodeeditor.html to implement features like jump to a line or colorize lines.

I found that if APIs like editor.revealLineInCenter(line) is called inside onEditorMount, it is not working, right? So I call API like revealLine() through the instance returned by getEditor(). But I have difficulty at highlighting code lines, I keep googling and found the API colorizeModelLine() that maybe useful but find little examples about its usage, can you give me a hint?

I have posted a related question at: microsoft/monaco-editor#1529, looking forward to answers.

Outdated webpack plugin usage?

The webpack plugin usage seems outdated - I guess you're supposed to do it something like this now?

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

module.exports = {
  configureWebpack: {
    plugins: [
      new MonacoEditorPlugin()
    ]
  }
}

Which didn't go well with npm run serve

ERROR  Error loading vue.config.js:
 ERROR  Error: Cannot find module 'monaco-editor\esm\vs\language\typescript\lib\typescriptServices'
Error: Cannot find module 'monaco-editor\esm\vs\language\typescript\lib\typescriptServices'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.resolve (internal/module.js:18:19)
    at resolveMonacoPath (c....\node_modules\monaco-editor-webpack-plugin\index.js:35:18)
    at Object.<anonymous> (c:.....\node_modules\monaco-editor-webpack-plugin\index.js:7:4)

So, I tried npm i -S monaco-editor, but that gave new interesting errors.. because it's probably a too new version.

Error: Cannot find module 'monaco-editor\esm\vs\editor\contrib\fontZoom\fontZoom'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.resolve (internal/module.js:18:19)
    at resolveMonacoPath (c<project-path>\node_modules\monaco-editor-webpack-plugin\index.js:21:18)
    at use.options.pre.featurePaths.map (c<project-path>\node_modules\monaco-editor-webpack-plugin\index.js:133:51)
    at Array.map (<anonymous>)
    at createLoaderRules (c<project-path>\node_modules\monaco-editor-webpack-plugin\index.js:133:31)
    at MonacoWebpackPlugin.apply (c<project-path>\node_modules\monaco-editor-webpack-plugin\index.js:71:19)
    at webpack (c<project-path>\node_modules\webpack\lib\webpack.js:37:12)
    at serve (c<project-path>\node_modules\@vue\cli-service\lib\commands\serve.js:112:22)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

Eventually I uninstalled both the monaco-editor and monaco-editor-webpack-plugin packages that were @ latest and did the ones in the package.json of the vue-monaco project, and then it seems to work better..

i.e. npm i -S [email protected] [email protected]

Maybe some updating is in order here to clarify and correct this?

Which version of monaco-editor and/or the webpack plugin needs to be installed?

when I use it in electron, Error: Cannot find module 'monaco-editor'

vue.esm.js?a026:1897 Error: Cannot find module 'monaco-editor'
    at Module._resolveFilename (module.js:543)
    at Function.Module._resolveFilename (D:\myProject\other\house365Spider\node_modules\electron\dist\resources\electron.asar\common\reset-search-paths.js:35)
    at Function.Module._load (module.js:473)
    at Module.require (module.js:586)
    at require (internal/module.js:11)
    at VueComponent.mounted (D:\myProject\other\house365Spider\node_modules\vue-monaco\dist\vue-monaco.js:93)
    at invokeWithErrorHandling (vue.esm.js?a026:1863)
    at callHook (vue.esm.js?a026:4222)
    at Object.insert (vue.esm.js?a026:3148)
    at invokeInsertHook (vue.esm.js?a026:6351)

Future plan for this project

So it seems there're a few bugs right now (which I can't confirm), I've no plan to fix them myself as I no longer use Vue 2.x, but PR is always welcome if you manage to fix them.

PR is also welcome for Vue 3.x support, I might do it myself in a few weeks if no one else does.

Example code throws errors.

Using the provided App.vue and webpack.config.js, the following errors are thrown at runtime:

image

App.vue

<template>
  <MonacoEditor class="editor" v-model="code" language="javascript" />
</template>

<script>
import MonacoEditor from 'vue-monaco'

export default {
  components: {
    MonacoEditor
  },

  data() {
    return {
      code: 'const noop = () => {}'
    }
  }
}
</script>

<style>
.editor {
  width: 600px;
  height: 800px;
}
</style>

webpack.config.js

// webpack.config.js
const MonacoEditorPlugin = require('monaco-editor-webpack-plugin')

module.exports = {
    plugins: [
        new MonacoEditorPlugin({

            // https://github.com/Microsoft/monaco-editor-webpack-plugin#options
            // Include a subset of languages support
            // Some language extensions like typescript are so huge that may impact build performance
            // e.g. Build full languages support with webpack 4.0 takes over 80 seconds
            // Languages are loaded on demand at runtime
            languages: ['javascript', 'css', 'html', 'typescript']
        })
    ]
}

package.json

{
  "name": "monaco-vue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "monaco-editor-webpack-plugin": "^3.0.1",
    "vue": "^2.6.11",
    "vue-monaco": "^1.2.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "vue-template-compiler": "^2.6.11"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

Any explanation would be greatly appreciated.

Error with Vite

Using Vite to build a vue project, with es module import like

import MonacoEditor from 'vue-monaco'
ReferenceError: require is not defined
    at a.mounted (vue-monaco.es.181a4dd2.js:6)
    at Mt (vendor.6a78aee7.js:6)
    at Qe (vendor.6a78aee7.js:6)
    at Object.insert (vendor.6a78aee7.js:6)
    at A (vendor.6a78aee7.js:6)
    at a.__patch__ (vendor.6a78aee7.js:6)
    at a.t._update (vendor.6a78aee7.js:6)
    at a.n (vendor.6a78aee7.js:6)
    at ui.get (vendor.6a78aee7.js:6)
    at ui.run (vendor.6a78aee7.js:6)

Error is from this block in the source

    } else {
      // ESM format so it can't be resolved by commonjs `require` in eslint
      // eslint-disable-next-line import/no-unresolved
      var monaco = require('monaco-editor');

      this.monaco = monaco;
      this.$nextTick(function () {
        _this.initMonaco(monaco);
      });
    }

I don't understand why the es-module build has require in it, but if I remove that and add

import * as monaco from 'monaco-editor';

I get up to the point where this issue vitejs/vite#1791 is relevant

theme 主题问题

只要我在配置new MonacoEditorPlugin里面languages添加语言选项,<MonacoEditor .. theme="vs-dark"/> vs-dark编辑器里背景色就变成白色了,去掉new MonacoEditorPlugin({}) 后,vs-dark颜色才恢复正常,是黑色背景,这是什么原因

使用问题

0.13.1版本用不了,替换新版本可以使用,onDidBlurEditor和onDidFocusEditor接口找不到

Using two editor instances in one component

I am using two editors in my component and noticed that the underlying editor instances don't seem to be separated. When I set the dark theme on one editor the other also uses it instantly.

I also noticed that options set on the one editor (like word wrap) sometimes leak to the other editor. I created a simple app to demonstrate the issue with version 1.0.0 of vue-monaco:

https://codesandbox.io/embed/vue-template-zoejm

It would be nice if the MonacoEditor would manage to separate the instances so they can be configured separately. By the way I never had any issues with leaking of the actual editor content.

Thanks!

Having issue with the theme

Having issues with the dark theme (vs-dark). Empty and small files are loaded with the dark them, large files loaded with the default white theme.

This is <TheEditor> component. I removed lots of code from the original component for demonstration purpose. Note that it does not uses v-model, instead it uses value and @change to interact with VueX store:

<template>
  <div class="the-editor">
    <MonacoEditor
      class="editor"
      :theme="codeEditor.theme"
      :language="codeEditor.language"
      :options="codeEditor.options"
      :value="codeEditor.content"
      @change="updateFile"
    />
  </div>
</template>

<script>
import MonacoEditor from 'vue-monaco';

export default {
  name: 'TheEditor',
  components: { MonacoEditor },
  computed: {
    code() {
      return this.$store.getters.code;
    },
    isEditMode() {
      return this.$store.getters.isEditMode;
    },
    codeEditor() {
      return {
        theme: 'vs-dark',
        language: this.code.language,
        content: this.code.content || '',
        options: {
          automaticLayout: true,
          readOnly: !this.isEditMode,
        },
      };
    },
  },
  methods: {
    updateFile(newVal) {
      const newFile = { ...this.code, content: newVal || '' };
      this.$store.commit({ type: 'updateFile', file: newFile });
    },
  },
};
</script>

<style lang="scss">
.the-editor{

  .editor {
    width: 100%;
    height: 100%;
  }
}
</style>

With the following vue.config.js file:

module.exports = {
  productionSourceMap: false,
  lintOnSave: false,
  configureWebpack: {
    node: {
      process: false, // Fix copy & paste bug
      module: 'empty', // Fix build warning
      fs: 'empty', // Fix build warning
    },
    plugins: [
      new MonocoEditorPlugin(),
    ],
  },
};

In any case, the dark theme CSS is not always loaded. Do you see why it happens?

can't access to editor instance

      <MonacoEditor
        class="editor"
        ref="editor"
        v-model="code"
        theme="gCodeFirst"
        language="GCodeLanguage"
        @editorWillMount="editorDidMount"
        :options="options"
      >
      </MonacoEditor>
    editorDidMount (editor) {
      // Register a new language
      editor.languages.register({ id: 'GCodeLanguage' })
      var e = this.$refs.editor.getEditor()
      console.log(e)
      ...............................................
     ...............................................

in the console I get undefined
this.$refs.editor ==> also does not give access to the instance
I need to use functions like getPosition(), setPosition() but i can't access the editor instance, only to the model

Error: Cannot find module 'monaco-editor\esm\vs\editor\contrib\gotoSymbol\goToCommands'

I am using below versions for monaco editor and its plugin

"monaco-editor": "0.19.0",
"monaco-editor-webpack-plugin": "1.8.1"

I am getting below error

 ...\node_modules\webpack-cli\bin\cli.js:265
                              throw err;
                              ^

 Error: Cannot find module 'monaco-editor\esm\vs\editor\contrib\gotoSymbol\goToCommands'
     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
     at Function.resolve (...\node_modules\v8-compile-cache\v8-compile-cache.js:166:23)
     at resolveMonacoPath (...\node_modules\monaco-editor-webpack-plugin\out\index.js:26:20)
     at use.options.pre.featurePaths.map (...\node_modules\monaco-editor-webpack-plugin\out\index.js:161:63)
     at Array.map (<anonymous>)
     at createLoaderRules (...\node_modules\monaco-editor-webpack-plugin\out\index.js:161:43)
     at MonacoEditorWebpackPlugin.apply (...\node_modules\monaco-editor-webpack-plugin\out\index.js:80:23)
     at webpack (...\node_modules\webpack\lib\webpack.js:47:13)
     at processOptions (...\node_modules\webpack-cli\bin\cli.js:256:16)
     at yargs.parse (...\node_modules\webpack-cli\bin\cli.js:373:3)
     at Object.parse (...\node_modules\webpack-cli\node_modules\yargs\yargs.js:567:18)
     at ...\node_modules\webpack-cli\bin\cli.js:49:8
     at Object.<anonymous> (...\node_modules\webpack-cli\bin\cli.js:375:3)
     at Module._compile (internal/modules/cjs/loader.js:778:30)
     at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
     at Module.load (internal/modules/cjs/loader.js:653:32)
     at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
     at Function.Module._load (internal/modules/cjs/loader.js:585:3)
     at Module.require (internal/modules/cjs/loader.js:692:17)
     at require (internal/modules/cjs/helpers.js:25:18)
     at Object.<anonymous> (...\node_modules\webpack\bin\webpack.js:156:2)
     at Module._compile (internal/modules/cjs/loader.js:778:30)
     at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
     at Module.load (internal/modules/cjs/loader.js:653:32)
     at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
     at Function.Module._load (internal/modules/cjs/loader.js:585:3)
     at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
     at startup (internal/bootstrap/node.js:283:19)
     at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
error: Error: webpack failed! [code 1]

I cannot find any recent issue or Stackoverflow page for this error with given version.

Could you please help?

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.