Search code examples
javascriptjquerymonaco-editor

How to initialize Microsoft Monaco editor in a browser using simple JavaScript or jQuery


I am trying to initialize a text/code editor using Microsoft Monaco. I would like to use core JavaScript or even jQuery but no NodeJS dependency. Is that possible?

Some relevant examples:

Get the value of Monaco Editor

Example in jsFiddle

I have the following code, which is not working:

    <!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="container" style="width:800px;height:600px;border:1px solid grey"></div>

<script type="text/javascript" src="https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs/loader.js"></script>


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

function save() {
   // get the value of the data
   var value = window.editor.getValue()
   saveValueSomewhere(value);     
}


</script>
</body>
</html>

Can anyone help?


Solution

  • I've added a working example below. Regarding your other question:

    I would like to use core JavaScript or even jQuery but no NodeJS dependency. Is that possible?

    monaco-editor IS written in JavaScript (TypeScript compiled to JavaScript) and does not use jQuery. Node is not really relevant in the context you've described.

    Please let me know if this helps.

    require.config({ paths: { 'vs': 'https://unpkg.com/monaco-editor@latest/min/vs' }});
    window.MonacoEnvironment = { getWorkerUrl: () => proxy };
    
    let proxy = URL.createObjectURL(new Blob([`
    	self.MonacoEnvironment = {
    		baseUrl: 'https://unpkg.com/monaco-editor@latest/min/'
    	};
    	importScripts('https://unpkg.com/monaco-editor@latest/min/vs/base/worker/workerMain.js');
    `], { type: 'text/javascript' }));
    
    require(["vs/editor/editor.main"], function () {
    	let editor = monaco.editor.create(document.getElementById('container'), {
    		value: [
    			'function x() {',
    			'\tconsole.log("Hello world!");',
    			'}'
    		].join('\n'),
    		language: 'javascript',
    		theme: 'vs-dark'
    	});
    });
    html, body, #container {
    	position: absolute;
    	left: 0;
    	top: 0;
    	width: 100%;
    	height: 100%;
    	margin: 0;
    	padding: 0;
    	overflow: hidden;
    }
    <script src="https://unpkg.com/monaco-editor@latest/min/vs/loader.js"></script>
    <div id="container"></div>