Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple monaco javascript editors so they don't share a global namespace?

I'd like to have multiple Monaco editors on a page, but each with the own set of globals. Variables created in one editor shouldn't be available as types in an another.

I've tried setting monaco.languages.typescript.javascriptDefaults.setCompilerOptions({isolatedModules: true}), but that didn't seem to effect these shared global types.

How can I create multiple monaco javascript editors so they don't share a global namespace?

// set up code for the Monaco Playground:
const container = document.getElementById("container");
const container1 = document.createElement("div");
const container2 = document.createElement("div");
container1.style.height="200px";
container1.style.border = "solid 2px black";
container1.style.marginBottom = "16px";
container2.style.height="200px";
container2.style.border = "solid 2px black";
container.appendChild(container1);
container.appendChild(container2);



// actual code:
monaco.editor.create(container1, {
    model: monaco.editor.createModel(`const abc = 123;`,
        "javascript",
        monaco.Uri.parse("js:editor1.js")
    )
});

monaco.editor.create(container2, {
    model: monaco.editor.createModel(
        "const value = abc; // should be typed as `any`, but is typed as `123` instead!",
        "javascript",
        monaco.Uri.parse("js:editor2.js")
    )
});

Try it in the playground: https://microsoft.github.io/monaco-editor/playground.html

like image 494
David Murdoch Avatar asked Dec 17 '20 21:12

David Murdoch


1 Answers

I found some discussion in https://github.com/microsoft/monaco-editor/issues/262 .

My temporary solution is to add export {} at the beginning of the code. Hopefully I can find a more elegant way to solve the problem.

// set up code for the Monaco Playground:
const container = document.getElementById("container");
const container1 = document.createElement("div");
const container2 = document.createElement("div");
container1.style.height = "200px";
container1.style.border = "solid 2px black";
container1.style.marginBottom = "16px";
container2.style.height = "200px";
container2.style.border = "solid 2px black";
container.appendChild(container1);
container.appendChild(container2);



// actual code:
monaco.editor.create(container1, {
    model: monaco.editor.createModel(
        `export {}\nconst abc = 123;`,
        "javascript",
        monaco.Uri.parse("js:editor1.js"),
    )
});

monaco.editor.create(container2, {
    model: monaco.editor.createModel(
        "export {}\nconst a = abc; // should be typed as `any`, but is typed as `123` instead!",
        "javascript",
        monaco.Uri.parse("js:editor2.js")
    )
});
like image 87
Yari Avatar answered Nov 15 '22 09:11

Yari