Create editor at runtime

Hello, I am new to bundling, and I followed the guide “Bundling Codemirror with Rollup”, writing this in my .html:

and this in my editor.js:
parent: document.querySelector("#editor1")

But I need to create multiple editors at runtime, how can I do? I cannot just create a function in editor.js that returns a new editor because it has a local scope in editor.bundle.js and I cannot call it from my html. Is there a way I can do this?

This seems more of a basic JavaScript question than a CodeMirror question. The easiest way around it is to put your function in the global scope (by assigning to window.someName) I guess.

1 Like

That is a good answer from @marijn. This process may seem very basic in JavaScript, but it took me a while to find these answer.

I am adding this code to help new developers experimenting with CodeMirror and facing some challenges.

In your editor.js file add something like this:

window["createEditor"] = function(element){
    return  new EditorView({
        parent: document.getElementById("editor"),
        extensions: [ basicSetup]
    });
}

Then your index.html should implement the function:

<html>
<body>
    <div id="editor"></div>
    <script src="editor.bundle.js"></script>
    <script>createEditor("editor");</script>
</body>
</html>

I hope it saves you some scratching head time.