Monaco Editor – Quick Start

Filed under: JavaScript

The Monaco editor is the workhorse that powers Visual Studio Code. Modern browsers can run the editor. The trick is quickly getting started.

I did a google search and found the documentation, but nothing on getting started. I ended up using the editor’s playground page to figure out how to set the editor for Jolt 9.

The Monaco Editor as of 0.7.0 comes with an amd loader and it expects all its files, including CSS files to be loaded from the same directory.

Note: the ~ in the code below comes from Razor templates where it signals to the template engine that the application root should replace the ~ character.

You’ll need to copy the files from node_modules/monaco-editor/min/vs to your preferred location of choice. Since I’m using ASP.NET Core, I use gulp to copy the files from node_modules to wwwroot/js/vs.

Here is condensed sample of how to set up the Monaco Editor, since I could not find a quick start elsewhere.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/css/admin.css" media="screen" rel="stylesheet" />
    <link href="~/js/vs/editor/editor.main.css" rel="stylesheet" />
</head>
<body>
   <div id="editor"> 

   </div>

    <script>var require = { paths: { 'vs': '/js/vs' } };</script>
    <script type="text/javascript" src="~/js/vs/loader.js"></script>
    <script type="text/javascript" src="~/js/vs/editor/editor.main.nls.js"></script>
    <script type="text/javascript" src="~/js/vs/editor/editor.main.js"></script>
    <script>
        "use strict";
        var el = document.getElementById('editor');
        el.style.height = '400px';
        el.style.width = '500px';

        // window.editor is accessible. 
        var editor = null;
        var init = function () {

            require(['vs/editor/editor.main'], function () {

                editor = monaco.editor.create(el, {
                    theme: 'vs-dark',
                    model: monaco.editor.createModel("#Test \np", "markdown")
                });

                editor.layout();
            });

            // no point in keeping this around.
            window.removeEventListener("load", init);
        };

        window.addEventListener("load", init);
    </script> 
</body>
</html>

Comments

comments

Nerdy Mishka