Sam
Sam

Reputation: 855

Import monaco editor using require js

I have installed monaco-editor using

npm install monaco-editor

now I want to require in my js file

so I have tried to require using

var monaco = require('monaco-editor');

but it is giving me module not found error.

Is there wrong I am doing?

Upvotes: 4

Views: 5830

Answers (3)

manikanta
manikanta

Reputation: 8500

In my case, I'm trying to load Monaco Editor in nw.js app which had require.js.

Usually Monaco Editor examples recommends using its 'Loader.js'. But if you already have another amd loader (ex: require.js), then you don't need to include & use Monaco's Loader.js. By this Github comment I got to know the Monaco's Loader.js will not do anything if it detects another amd loader.

This official sample might be useful.


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    </head>
    <body>
        <h2>Monaco Editor Sample - Loading with requirejs</h2>
        <div id="container" style="width: 800px; height: 600px; border: 1px solid grey"></div>

        <script
            src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"
            integrity="sha256-0SGl1PJNDyJwcV5T+weg2zpEMrh7xvlwO4oXgvZCeZk="
            crossorigin="anonymous"
        ></script>
        <script>
            require.config({ paths: { vs: '../node_modules/monaco-editor/min/vs' } });

            require(['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>
    </body>
</html>

Upvotes: 0

SimperT
SimperT

Reputation: 2867

Monaco-editor uses a custom AMD style module loader. the loader.js will result in the global require being set to Monaco-editor's loader.

The samples GitHub has many examples of using the editor in different contexts.

Check out how they solve your problem in the Electorn samples index.html. After persisting the Monaco-editor custom loader you would use it like in most of the examples out there. It is an AMD style loader so the syntax differs from node var me = require('monaco') . I am not sure if it is possible to use like node loader but after loading loader.js and persisting the require to some variable such as amdRequire you will use such as:

amdRequire(['vs/editor/editor.main'], function () 
{ 
    // your code using monaco ns here
    monaco.editor.create( document.getElementById('elementId'), {} );
})

Upvotes: 4

Mesut
Mesut

Reputation: 242

They just released ESM distribution which is compatible with webpack etc. Check out the docs here.

Also there are many examples for using monaco with webpack, parcel an so on. See all.

Upvotes: 4

Related Questions