Skip to content

Dual package hazard #3

@jcbhmr

Description

@jcbhmr

This package seems to encounter the dual package hazard where the same code is bundled twice. Once for CJS and once for ESM in a final browser dist bundle. There's no actual published npm packages that have this as a dependency (yet), but I encountered this in dev like this: https://stackblitz.com/edit/vitejs-vite-4y95fw?file=html-prompt.js,node-util-types.cjs,main.js,dist%2Fassets%2Findex-bc7f32d1.js&terminal=dev
(simulated by one mjs file and one cjs file that could easily be actual package.json packages)

https://nodejs.org/api/packages.html#packages_dual_package_hazard

The fix to this is to use CJS as the main implementation, and either a) do nothing and let Node.js infer named exports or b) explicitly export things in a wrapper.mjs or similar file or c) only support ESM with NO CJS build

// wrapper.mjs
import moduleExports from "./index.cjs";
export const { a, b, c } = moduleExports;

There's an open issue on typescript github to support changing file extensions at tsc buildtime. That hasn't been encouraged since it's mostly used to cause the not-so-great dual package hazard. Instead TS team seems to recommend that you just build an ESM or CJS and then wrap it in another .mjs or .cjs file as a facade for the other module system. microsoft/TypeScript#49462

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions