diff --git a/docs/runtime/modules.md b/docs/runtime/modules.md index da9bc92534..5ba4956cee 100644 --- a/docs/runtime/modules.md +++ b/docs/runtime/modules.md @@ -156,3 +156,90 @@ In the spirit of treating TypeScript as a first-class citizen, the Bun runtime w ``` If you aren't a TypeScript user, you can create a [`jsconfig.json`](https://code.visualstudio.com/docs/languages/jsconfig) in your project root to achieve the same behavior. + +## CommonJS + +Bun has native support for CommonJS modules (added in Bun v0.6.5). + +In Bun's JavaScript runtime, `require` can be used by both ES Modules and CommonJS modules. + +In Bun, you can `require()` ESM modules from CommonJS modules. + +| Module Type | `require()` | `import * as` | +| ----------- | ---------------- | ----------------------------------------------------------------------- | +| ES Module | Module Namespace | Module Namespace | +| CommonJS | module.exports | `default` is `module.exports`, keys of module.exports are named exports | + +If the target module is an ES Module, `require` returns the module namespace object (equivalent to `import * as`). +If the target module is a CommonJS module, `require` returns the `module.exports` object. + +### What is a CommonJS module? + +In 2016, ECMAScript added support for [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). ES Modules are the standard for JavaScript modules. However, millions of npm packages still use CommonJS modules. + +CommonJS modules are modules that use `module.exports` to export values. Typically, `require` is used to import CommonJS modules. + +```ts +// my-commonjs.cjs +const stuff = require("./stuff"); +module.exports = { stuff }; +``` + +The biggest difference between CommonJS and ES Modules is that CommonJS modules are synchronous, while ES Modules are asynchronous. There are other differences too, like ES Modules support top-level `await` and CommonJS modules don't. ES Modules are always in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode), while CommonJS modules are not. Browsers do not have native support for CommonJS modules, but they do have native support for ES Modules (`