Skip to content

build: migrate from CommonJS to ESM #687

Open

Description

Context

The extension is currently CommonJS. This blocks us from consuming a growing number of modern, ESM-only dependencies. Concrete recent example: p-limit@4+ is pure ESM, which is why #685 introduced an in-house ConcurrencyLimiter instead of pulling a battle-tested library off the shelf.

vscode-cosmosdb (sibling extension, same org) has already completed this migration on main, so there is a working reference for what the end state looks like.

What this issue tracks

The actual migration. The choice of build system, test runner, linter/formatter, and Node target is still to be made as part of this work. Options to evaluate:

  • Build: Vite (what vscode-cosmosdb chose) vs. continuing with webpack in ESM mode vs. esbuild vs. tsup.
  • Test runner: Vitest (what vscode-cosmosdb chose) vs. Jest with ESM support vs. node:test.
  • Linter/formatter: continue with ESLint + Prettier vs. switch to oxlint / oxfmt (faster, what vscode-cosmosdb chose).
  • Node engine: bump to >=22 (matches vscode-cosmosdb) or hold lower.
  • TypeScript: bump to latest (vscode-cosmosdb is on TS 6.x).

A short design note before the implementation PR is expected.

Concrete benefits

  • Unblocks ESM-only dependencies: p-limit, chalk, node-fetch, nanoid, execa, and a long and growing tail.
  • Smaller bundles and faster cold start (tree-shaking is much more effective on ESM).
  • Faster build/test feedback loops if we adopt Vite + Vitest (sub-second incremental builds reported by vscode-cosmosdb).
  • Aligns us with vscode-cosmosdb tooling, lowering the cognitive cost of moving between repos.
  • Removes the mocha-based VS Code test runner pain point. The legacy @vscode/test-electron + mocha pipeline does not love ESM; vscode-cosmosdb works around this with a pretest hook that drops a CJS package.json into out/. The upstream story is that this runner has either already been removed or is on track to be removed, so the workaround should be temporary or unnecessary depending on when we land.

Known costs / risks

  • Touches every file with a relative import (./foo -> ./foo.js in many ESM toolchains, depending on bundler/moduleResolution).
  • Webpack config rewrite or replacement.
  • Jest -> alternative test runner migration (touches every test file's imports and mocks; jest.mock does not have a 1:1 ESM equivalent).
  • __dirname / require removal from the codebase.
  • Potential VS Code engine version bump.
  • One-shot reviewer load: the diff will be large.

References

Acceptance criteria

  • Decision recorded for each open choice above.
  • All existing tests pass under the new test runner (or a documented, scoped exception list).
  • Extension activates, builds, packages, and ships exactly as before.
  • CI green.
  • No CJS-only fallback shims remaining (e.g. no pretest-style package.json rewrite needed once the upstream test runner removal lands).

Activity

  1. tnaum-ms commented on May 28, 2026

    @tnaum-ms
    CollaboratorAuthor

    Tooling trade-offs (summary from review discussion)

    Captured here for context before we make the decisions called out above.

    Vitest (vs. Jest)

    What it is. Test runner from the Vite team. Jest-compatible API, native ESM, native TypeScript via esbuild, reuses your Vite config so the test environment matches the build environment. describe/it/expect/beforeEach are unchanged; jest.fn() -> vi.fn(), jest.mock() -> vi.mock().

    Why teams move off Jest:

    1. Jest + ESM is still painful in 2026. Officially "experimental", requires --experimental-vm-modules, and jest.mock() of ESM modules has sharp edges (hoisting, partial mocks, top-level await). For a project migrating to ESM, dragging Jest along is the worst of both worlds.
    2. Speed. Vitest reuses Vite's transform pipeline. In watch mode it re-runs only tests affected by changed modules. ~2-5x cold start, often >10x in watch.
    3. No ts-jest / @swc/jest. TS via esbuild by default.
    4. Single config. One vite.config.ts for build and test. No duplicate path aliases or moduleNameMapper.
    5. Browser-mode tests. Run the same test file in Node or in a real browser via Playwright. Useful for webview tests.

    Why not leave Jest:

    1. Snapshot format and jest.mock semantics are close but not 100% identical. Mocks sometimes need a small rewrite.
    2. The long tail of jest-* matchers / reporters is shorter on the Vitest side (the popular ones are covered).
    3. Jest --projects for monorepos is more battle-tested than Vitest workspaces.
    4. Heavy investment in custom Jest resolvers/transformers means real porting work.

    For this repo: ~1900 tests, mostly pure unit tests with light mocking. Port is mechanical, mostly jest. -> vi. find-and-replace.

    Vite (vs. webpack)

    • Vite is a dev-server + bundler optimized for ESM. Dev mode serves modules natively (no bundling in dev). Prod build uses Rollup.
    • Pro: dramatically faster dev/watch. Simple config. ESM-first.
    • Con: webpack still has a richer plugin ecosystem for VS Code extension quirks (CJS-only native modules, asset copying, polyfills). May need small Vite plugins for WASM copying, externalizing vscode, conditional driver imports.

    oxlint + oxfmt (vs. ESLint + Prettier)

    • Rust-based, ESLint/Prettier-compatible. ~50-100x faster.
    • Con: rule coverage is ~80-90% of popular ESLint rules (especially TypeScript-specific ones). May need to run both for a while ("fast first-pass" + "thorough CI pass").

    Node >=22

    • Pro: native fetch, --watch, node:test, top-level await, import.meta.resolve. Drop polyfill deps.
    • Con: VS Code ships its own Node runtime. The extension's engines.vscode must be high enough that the bundled Node is >=22, which cuts off users on older VS Code. vscode-cosmosdb picked ^1.109.0 (recent but not bleeding-edge). Decide against installed-VS-Code-version telemetry.

    Lowest-risk recommendation

    Vite + Vitest, keep ESLint + Prettier for now. Get 90% of the benefit with the smallest blast radius. oxlint/oxfmt is a separate, smaller decision later. The Node 22 bump is the only choice with real user-facing impact and deserves its own discussion.

  2. tnaum-ms commented on May 28, 2026

    @tnaum-ms
    CollaboratorAuthor

    Build tool: Vite vs. esbuild vs. mixed (follow-up to the tooling summary above)

    What vscode-cosmosdb actually picked

    All-Vite, no esbuild as a separate tool. Two Vite configs:

    • vite.config.ext.mjs — extension host in Vite's "library mode" (build.lib), target: 'node22', ESM output (main.mjs), externalizes vscode + vs + Node built-ins, bundles everything else.
    • vite.config.views.mjs — webviews with @vitejs/plugin-react, dev server, Monaco workers, prod-only bundle analyzer.

    esbuild is still in the picture, just underneath Vite (Vite uses it for dev transform). They don't invoke it directly.

    What that decision cost them

    Reading their configs, they paid for "Vite everywhere" in non-trivial ways:

    1. CJS-interop banner injected into every output file:

      import { createRequire } from 'module';
      const require = createRequire(import.meta.url);

      Needed because the output is ESM but the bundled CJS packages still call require() at runtime.

    2. tslib aliased to its ESM build. Long comment in the ext config explains: Rolldown's __toESM interop helper crashes on legacy Azure SDKs (@azure/arm-cosmosdb, @azure/arm-postgresql, @azure/arm-postgresql-flexible) compiled with importHelpers: true. The fix is tslib: path.resolve(__dirname, 'node_modules/tslib/tslib.es6.mjs'). A genuine landmine, defused with a one-line alias once you know what to look for.

    3. Six custom Vite plugins: vite-plugin-no-extension-imports (guards webview code from importing vscode), vite-plugin-webview-entry (dev-mode entry shim), vite-plugin-react-refresh-preamble, vite-plugin-monaco-workers, vite-plugin-inline-css, vite-plugin-bundle-report.

    4. A dedicated docs/webview-build.md that the config has anchor links into. They explicitly designed the configs to be terse and to defer rationale to that doc.

    So: meaningful investment, but they bought consistency. One tool, one mental model, one plugin API across both targets, and Vitest plugs in for free (shared config, shared transforms, shared resolver).


    Option A: All-Vite (mirror vscode-cosmosdb)

    For:

    • One tool, one config language, one plugin model. Sharable plugin code across targets.
    • Vitest integration is automatic — same resolver and transforms as the build, so tests can't disagree with prod about how modules resolve.
    • Future bundles slot in cheaply (docs site, embedded playground, sample app).
    • One watch process model. Easier to reason about in CI and concurrently setups.
    • vscode-cosmosdb already paved this path. Lower org-level support cost. Whatever rough edges exist, they already mapped them. We can lift their plugins and docs/webview-build.md largely verbatim.

    Against:

    • Vite library mode for Node is its weakest mode. Vite is optimized for SPAs in a browser. Extension-host code is small Node ESM with weird CJS deps — exactly the corner where you trip on Rolldown interop bugs (hence the tslib alias and the createRequire banner).
    • No dev-server/HMR benefit for the extension host. The extension host doesn't HMR. You pay for Vite's complexity and get only its prod bundler.
    • You will probably write custom plugins. cosmosdb wrote six.
    • Visibly slower than esbuild for the ext target (not by a lot).

    Option B: esbuild-for-ext + Vite-for-webviews

    For:

    • esbuild handles Node CJS-interop natively. --platform=node --format=esm --external:vscode just works on the kinds of deps that made cosmosdb write the tslib alias.
    • Config is tiny. A build.mjs of <50 lines replaces all of vite.config.ext.mjs plus its workarounds.
    • Each tool used in its sweet spot: esbuild for fast Node bundling, Vite for the actual browser-like target (webviews + HMR).
    • The webview side still gets Vitest for free. You only "lose" Vitest-via-shared-config for the extension-host tests, and those can still run under Vitest in Node mode using its own esbuild transform — no Vite config needed.

    Against:

    • Two tools in the toolbox. New maintainers learn two configs, two plugin APIs, two watch commands.
    • No plugin code reuse. The "guard webview code from importing vscode" plugin cosmosdb wrote is genuinely useful and would have to be written twice (an esbuild plugin + a Vite plugin) to apply to both targets.
    • Diverges from the sibling extension. Higher cognitive switching cost between repos. If the cosmosdb team solves a future problem with a Vite plugin, we can't lift it directly.
    • One more place to wire l10n / asset copy / package.json transforms. cosmosdb does all of that in vite-plugin-static-copy blocks; split builds duplicate it.

    Option C: All-esbuild

    For:

    • Tiniest config. Single binary, near-instant builds.
    • Best CJS-interop story of any option.

    Against:

    • No HMR for webviews. Real productivity loss during webview development.
    • No Vite plugin ecosystem (Monaco workers, React Refresh, SCSS, etc.). You'd reinvent or do without.
    • esbuild's plugin API is much smaller than Vite/Rollup's. Some things (asset graph manipulation, virtual modules) are harder.
    • Diverges most from cosmosdb.

    Recommendation

    Start with Option A (all-Vite, mirror cosmosdb). The marginal cost is low because we can copy their configs, adapt the aliases, reuse their plugins, and reuse their docs/webview-build.md. The long-term consistency benefit across the two sibling repos is real.

    If Vite library mode for Node keeps biting us (more Rolldown interop bugs surface, build times become noticeable, the plugin maintenance burden grows), dropping to Option B is a one-day refactor — the webview side and the Vitest setup don't have to change. So the decision is cheap to revisit.

    Option C is not recommended for this codebase given the webview complexity (Monaco, React, SCSS).

  3. tnaum-ms commented on Sep 21, 2026

    @tnaum-ms
    CollaboratorAuthor

    Risk worth adding to the register: the dual-package hazard

    We just spent three months shipping a silent data bug caused by exactly the mechanism this migration will touch repo-wide. Details in #933; summarising here because the "Known costs / risks" list above does not currently name it.

    What happened. bson@7 declares split export conditions:

    "exports": {
      "default": {
        "import":  "./lib/bson.node.mjs",
        "require": "./lib/bson.cjs"
      }
    }

    Three call sites used await import('bson'). Webpack resolved those through the import condition and bundled the ESM build, while mongodb and every static import … from 'bson' (which swc emits as require) resolved the CJS build. Two copies, two sets of classes, so every instanceof ObjectId check against driver values returned false.

    The schema analyzer then classified ObjectId, Double, Int32, Long, Decimal128, Binary, Code, DBRef and Timestamp as plain objects and enumerated their internals — autocompletion offered _id.buffer and rating.value instead of _id and rating. MinKey/MaxKey vanished from the output entirely.

    Why it matters here. Three properties made this expensive, and all three are amplified by an ESM migration:

    1. No error. Nothing threw. EJSON.stringify duck-types on _bsontype, so serialisation and rendering kept working perfectly — only type inference broke. It took a user report to notice.
    2. The trigger was a build-config change, not a code change. The call sites had been there since March and were harmless, because swc downlevelled import() to require(). The bug appeared when ignoreDynamic: true was added to the swc loader so webpack could split lazy dependencies. Nobody touched the affected code.
    3. instanceof across package copies is invisible to the type system. TypeScript cannot see it, lint cannot see it, and the unit tests passed because they construct values from the same copy the assertion uses. It only reproduces in a bundled build.

    Concrete suggestions for this migration:

    • Add "duplicate copies of a dependency from split import/require export conditions" to the risks list. Every dependency whose classes we compare with instanceof is exposed — bson is the one that bit us, but it is not the only candidate.
    • Since the whole codebase flips to import, the CJS copy becomes the anomaly rather than the ESM one. The failure mode inverts but does not go away, and any dependency still resolved through require (transitively, via a non-migrated package) reintroduces it.
    • Worth a CI guard rather than vigilance. Ours is a one-liner, because webpack does not clean dist/:
      grep -c vendors-node_modules_bson_lib_bson_node_mjs dist/main.js   # must be 0
      A generalised version — assert no module specifier resolves to two distinct files in the bundle — would be cheap insurance for the migration and afterwards.
    • Prefer duck-typing over instanceof at package boundaries where a discriminator exists. We added a _bsontype fallback to BSONTypes.inferType() so the analyzer degrades correctly rather than silently, independent of how the bundler resolves things.

    The three import sites now carry an inline comment pointing back at this issue, so whoever does the migration meets the constraint at the place where it would be reintroduced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions