Skip to content

Support require(esm) in Node.js to avoid dual package hazard #321

Open
@fabon-f

Description

@fabon-f

(This proposal is same to fullcalendar/temporal-polyfill#62)

// in Node.js REPL
const { Temporal: Temporal1 } = await import('@js-temporal/polyfill')
const { Temporal: Temporal2 } = require('@js-temporal/polyfill')
Temporal2.Now.instant() instanceof Temporal2.Instant // true
Temporal2.Now.instant() instanceof Temporal1.Instant // false!!!

Temporal object exported from ESM and CJS is actually different, so identifying the object type by instanceof can cause the bug. (real world example with Luxon: 11ty/eleventy#3674)

Dual package hazard can be minimized by adding module-sync export condition. If Node.js supports require(esm), require and import returns identical module object from ESM, so instanceof works fine.

The module-sync condition is simply ignored in older versions of Node.js (no downside).

https://nodejs.org/docs/latest-v22.x/api/packages.html#conditional-exports

package.json should be like below. (perhaps types in module-sync is unnecessary, because TypeScript ignores module-sync export condition)

{
	"exports": {
		".": [
			{
				// add this
				"module-sync": {
					"types": "./index.d.ts",
					"default": "./dist/index.esm.js"
				},
				"import": {
					"types": "./index.d.ts",
					"default": "./dist/index.esm.js"
				},
				"require": {
					"types": "./index.d.cts",
					"default": "./dist/index.cjs"
				},
				"default": "./dist/index.cjs"
			},
			"./dist/index.cjs"
		]
	}
}

Note that Node.js v23, v22, and v20 already support require(esm). Node.js v18 will reach EOL in next month. Therefore, most users (except few users using legacy Node.js) will benefit from this change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions