如何创建多个Monaco JavaScript编辑器,使它们不共享全局命名空间?

11

我想在页面上有多个Monaco编辑器,但每个编辑器都有自己的全局变量集。在一个编辑器中创建的变量不应作为其他编辑器中的类型可用。

我尝试设置monaco.languages.typescript.javascriptDefaults.setCompilerOptions({isolatedModules: true}),但似乎没有影响这些共享的全局类型。

如何创建多个monaco javascript编辑器,使它们不共享全局命名空间?

// 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")
    )
});

在游乐场中尝试它:https://microsoft.github.io/monaco-editor/playground.html

2个回答

1
我在https://github.com/microsoft/monaco-editor/issues/262中找到了一些讨论。
我的临时解决方案是在代码开头添加export {}。希望我能找到更优雅的解决方法。
// 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")
    )
});

0
有点晚了,但在我的情况下,改变你提到的设置解决了它:
旧的:

monaco.languages.typescript.javascriptDefaults.setCompilerOptions({isolatedModules: true})

新:

monaco.languages.typescript.typescriptDefaults.setCompilerOptions({isolatedModules: true})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接