Search code examples
monaco-editoresbuild

Unexpected usage when bundled using esbuild


The following simple setup works when bundled using webpack, but not on esbuild. There is no issue in bundling, esbuild spits out all the files correctly, but somehow getting this error on browser. Any idea about the issue?

index.js

import * as monaco from "monaco-editor";

self.MonacoEnvironment = {
  getWorkerUrl: function (moduleId, label) {
    if (label === "typescript" || label === "javascript") {
      return "./ts.worker.bundle.js";
    }
    return "./editor.worker.bundle.js";
  },
};

monaco.editor.create(document.getElementById("container"), {
  value: ["function x() {", '\tconsole.log("Hello world!");', "}"].join("\n"),
  language: "javascript",
});

Esbuild Config

const esbuild = require("esbuild");

esbuild.build({
  entryPoints: {
    app: "./index.js",
    "editor.worker": "monaco-editor/esm/vs/editor/editor.worker.js",
    "ts.worker": "monaco-editor/esm/vs/language/typescript/ts.worker",
  },
  globalName: "self",
  entryNames: "[name].bundle",
  bundle: true,
  outdir: "./dist",
  loader: {
    ".ttf": "file",
  },
});

Log From Browser Console

app.bundle.js:2393 Uncaught Error: Unexpected usage

Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule (app.bundle.js:16294)
    at app.bundle.js:17060
    at app.bundle.js:2393

Solution

  • This line looks problematic:

    globalName: "self",
    

    In the browser, self is already a built-in variable: https://developer.mozilla.org/en-US/docs/Web/API/Window/self. Shadowing it could potentially be breaking Monaco. Your code appears to work if you just remove that line.