{"id":17716347,"url":"https://github.com/nodejs/package-examples","last_synced_at":"2025-10-16T17:50:50.860Z","repository":{"id":259213173,"uuid":"873161916","full_name":"nodejs/package-examples","owner":"nodejs","description":"Repository documenting package shipping patterns ","archived":false,"fork":false,"pushed_at":"2024-12-21T07:55:08.000Z","size":35,"stargazers_count":25,"open_issues_count":2,"forks_count":3,"subscribers_count":34,"default_branch":"main","last_synced_at":"2025-06-10T20:29:18.637Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nodejs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-10-15T17:46:38.000Z","updated_at":"2025-06-06T23:32:55.000Z","dependencies_parsed_at":"2025-04-18T20:32:46.546Z","dependency_job_id":"e4c44ea4-d301-4ab4-a1e4-17484b2ab174","html_url":"https://github.com/nodejs/package-examples","commit_stats":null,"previous_names":["nodejs/package-examples"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/nodejs/package-examples","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fpackage-examples","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fpackage-examples/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fpackage-examples/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fpackage-examples/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nodejs","download_url":"https://codeload.github.com/nodejs/package-examples/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fpackage-examples/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259778007,"owners_count":22909771,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-25T13:11:51.242Z","updated_at":"2025-10-16T17:50:50.795Z","avatar_url":"https://github.com/nodejs.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Node.js package shipping patterns\n\n\u003e [!NOTE]  \n\u003e This repository is currently under construction. It's meant to replace the sections in the Node.js package documentation for documenting package shipping patterns, the pros and cons, and guidelines for CJS to ESM migration.\n\nA team is being formed to get this effort up and going! See [Issue #3](https://github.com/nodejs/package-examples/issues/3) for details.\n\n⚒️ We are working on a [guide](./guide/) about how package configurations. See [contribution guide](./CONTRIBUTING.md) on how to contribute to it.\n\n## Previous documents from package.md in Node.js API documentation\n\n\u003e [!NOTE]  \n\u003e The following document is copied from the old package.md as-is, it will be in the README.md\n\u003e temporarily until we work out better and more up-to-date examples and documentation\n\u003e in this repository.\n\u003e A lot of the information below been outdated since Node.js started to support `require(esm)`.\n\u003e Do not follow the documentation below for new packages for the time being.\n\nPrior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with `package.json` [`\"main\"`][] specifying the\nCommonJS entry point and `package.json` `\"module\"` specifying the ES module\nentry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) the top-level `\"module\"` field.\n\nNode.js can now run ES module entry points, and a package can contain both\nCommonJS and ES module entry points (either via separate specifiers such as\n`'pkg'` and `'pkg/es-module'`, or both at the same specifier via [Conditional\nexports][]). Unlike in the scenario where top-level `\"module\"` field is only used by bundlers,\nor ES module files are transpiled into CommonJS on the fly before evaluation by\nNode.js, the files referenced by the ES module entry point are evaluated as ES\nmodules.\n\n### Dual package hazard\n\nWhen an application is using a package that provides both CommonJS and ES module\nsources, there is a risk of certain bugs if both versions of the package get\nloaded. This potential comes from the fact that the `pkgInstance` created by\n`const pkgInstance = require('pkg')` is not the same as the `pkgInstance`\ncreated by `import pkgInstance from 'pkg'` (or an alternative main path like\n`'pkg/module'`). This is the “dual package hazard,” where two versions of the\nsame package can be loaded within the same runtime environment. While it is\nunlikely that an application or package would intentionally load both versions\ndirectly, it is common for an application to load one version while a dependency\nof the application loads the other version. This hazard can happen because\nNode.js supports intermixing CommonJS and ES modules, and can lead to unexpected\nbehavior.\n\nIf the package main export is a constructor, an `instanceof` comparison of\ninstances created by the two versions returns `false`, and if the export is an\nobject, properties added to one (like `pkgInstance.foo = 3`) are not present on\nthe other. This differs from how `import` and `require` statements work in\nall-CommonJS or all-ES module environments, respectively, and therefore is\nsurprising to users. It also differs from the behavior users are familiar with\nwhen using transpilation via tools like [Babel][] or [`esm`][].\n\n### Writing dual packages while avoiding or minimizing hazards\n\nFirst, the hazard described in the previous section occurs when a package\ncontains both CommonJS and ES module sources and both sources are provided for\nuse in Node.js, either via separate main entry points or exported paths. A\npackage might instead be written where any version of Node.js receives only\nCommonJS sources, and any separate ES module sources the package might contain\nare intended only for other environments such as browsers. Such a package\nwould be usable by any version of Node.js, since `import` can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.\n\nA package might also switch from CommonJS to ES module syntax in a [breaking\nchange](https://semver.org/) version bump. This has the disadvantage that the\nnewest version of the package would only be usable in ES module-supporting\nversions of Node.js.\n\nEvery pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:\n\n1. The package is usable via both `require` and `import`.\n2. The package is usable in both current Node.js and older versions of Node.js\n   that lack support for ES modules.\n3. The package main entry point, e.g. `'pkg'` can be used by both `require` to\n   resolve to a CommonJS file and by `import` to resolve to an ES module file.\n   (And likewise for exported paths, e.g. `'pkg/feature'`.)\n4. The package provides named exports, e.g. `import { name } from 'pkg'` rather\n   than `import pkg from 'pkg'; pkg.name`.\n5. The package is potentially usable in other ES module environments such as\n   browsers.\n6. The hazards described in the previous section are avoided or minimized.\n\n#### Approach #1: Use an ES module wrapper\n\nWrite the package in CommonJS or transpile ES module sources into CommonJS, and\ncreate an ES module wrapper file that defines the named exports. Using\n[Conditional exports][], the ES module wrapper is used for `import` and the\nCommonJS entry point for `require`.\n\n```json\n// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"exports\": {\n    \"import\": \"./wrapper.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n```\n\nThe preceding example uses explicit extensions `.mjs` and `.cjs`.\nIf your files use the `.js` extension, `\"type\": \"module\"` will cause such files\nto be treated as ES modules, just as `\"type\": \"commonjs\"` would cause them\nto be treated as CommonJS.\nSee [Enabling ESM][].\n\n```cjs\n// ./node_modules/pkg/index.cjs\nexports.name = 'value';\n```\n\n```js\n// ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n```\n\nIn this example, the `name` from `import { name } from 'pkg'` is the same\nsingleton as the `name` from `const { name } = require('pkg')`. Therefore `===`\nreturns `true` when comparing the two `name`s and the divergent specifier hazard\nis avoided.\n\nIf the module is not simply a list of named exports, but rather contains a\nunique function or object export like `module.exports = function () { ... }`,\nor if support in the wrapper for the `import pkg from 'pkg'` pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:\n\n```js\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n```\n\nThis approach is appropriate for any of the following use cases:\n\n* The package is currently written in CommonJS and the author would prefer not\n  to refactor it into ES module syntax, but wishes to provide named exports for\n  ES module consumers.\n* The package has other packages that depend on it, and the end user might\n  install both this package and those other packages. For example a `utilities`\n  package is used directly in an application, and a `utilities-plus` package\n  adds a few more functions to `utilities`. Because the wrapper exports\n  underlying CommonJS files, it doesn't matter if `utilities-plus` is written in\n  CommonJS or ES module syntax; it will work either way.\n* The package stores internal state, and the package author would prefer not to\n  refactor the package to isolate its state management. See the next section.\n\nA variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. `\"./module\"`, to point to an all-ES module-syntax\nversion of the package. This could be used via `import 'pkg/module'` by users\nwho are certain that the CommonJS version will not be loaded anywhere in the\napplication, such as by dependencies; or if the CommonJS version can be loaded\nbut doesn't affect the ES module version (for example, because the package is\nstateless):\n\n```json\n// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./wrapper.mjs\"\n  }\n}\n```\n\n#### Approach #2: Isolate state\n\nA [`package.json`][] file can define the separate CommonJS and ES module entry\npoints directly:\n\n```json\n// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"exports\": {\n    \"import\": \"./index.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n```\n\nThis can be done if both the CommonJS and ES module versions of the package are\nequivalent, for example because one is the transpiled output of the other; and\nthe package's management of state is carefully isolated (or the package is\nstateless).\n\nThe reason that state is an issue is because both the CommonJS and ES module\nversions of the package might get used within an application; for example, the\nuser's application code could `import` the ES module version while a dependency\n`require`s the CommonJS version. If that were to occur, two copies of the\npackage would be loaded in memory and therefore two separate states would be\npresent. This would likely cause hard-to-troubleshoot bugs.\n\nAside from writing a stateless package (if JavaScript's `Math` were a package,\nfor example, it would be stateless as all of its methods are static), there are\nsome ways to isolate state so that it's shared between the potentially loaded\nCommonJS and ES module instances of the package:\n\n1. If possible, contain all state within an instantiated object. JavaScript's\n   `Date`, for example, needs to be instantiated to contain state; if it were a\n   package, it would be used like this:\n\n   ```js\n   import Date from 'date';\n   const someDate = new Date();\n   // someDate contains state; Date does not\n   ```\n\n   The `new` keyword isn't required; a package's function can return a new\n   object, or modify a passed-in object, to keep the state external to the\n   package.\n\n2. Isolate the state in one or more CommonJS files that are shared between the\n   CommonJS and ES module versions of the package. For example, if the CommonJS\n   and ES module entry points are `index.cjs` and `index.mjs`, respectively:\n\n   ```cjs\n   // ./node_modules/pkg/index.cjs\n   const state = require('./state.cjs');\n   module.exports.state = state;\n   ```\n\n   ```js\n   // ./node_modules/pkg/index.mjs\n   import state from './state.cjs';\n   export {\n     state,\n   };\n   ```\n\n   Even if `pkg` is used via both `require` and `import` in an application (for\n   example, via `import` in application code and via `require` by a dependency)\n   each reference of `pkg` will contain the same state; and modifying that\n   state from either module system will apply to both.\n\nAny plugins that attach to the package's singleton would need to separately\nattach to both the CommonJS and ES module singletons.\n\nThis approach is appropriate for any of the following use cases:\n\n* The package is currently written in ES module syntax and the package author\n  wants that version to be used wherever such syntax is supported.\n* The package is stateless or its state can be isolated without too much\n  difficulty.\n* The package is unlikely to have other public packages that depend on it, or if\n  it does, the package is stateless or has state that need not be shared between\n  dependencies or with the overall application.\n\nEven with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.\n\nAs with the previous approach, a variant of this approach not requiring\nconditional exports for consumers could be to add an export, e.g.\n`\"./module\"`, to point to an all-ES module-syntax version of the package:\n\n```json\n// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./index.mjs\"\n  }\n}\n```\n\n[Babel]: https://babeljs.io/\n[Conditional exports]: https://nodejs.org/api/packages.html#conditional-exports\n[Enabling ESM]: https://nodejs.org/api/esm.html#enabling\n[`esm`]: https://github.com/standard-things/esm#readme\n[`main`]: https://nodejs.org/api/packages.html#main\n[`package.json`]: https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnodejs%2Fpackage-examples","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnodejs%2Fpackage-examples","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnodejs%2Fpackage-examples/lists"}