Bun, a modern JavaScript runtime, has made strides in supporting both CommonJS (CJS) and ES Modules (ESM). As of Bun version 0.6.5, it natively implements CommonJS, allowing developers to use both module systems interchangeably within their applications.
Automatic Transpilation
Bun does not automatically transpile CJS modules to ESM. Instead, it allows for seamless interoperability between the two formats. This means that you can `import` or `require` CJS modules in an ESM context without needing to convert the modules explicitly. For instance:
javascript
import { stuff } from "./my-commonjs.cjs";
const myStuff = require("./my-commonjs.cjs");
This flexibility is particularly useful as many existing npm packages still rely on CommonJS, and Bun's design aims to accommodate this reality while promoting ESM as the preferred format for new projects[2][3].
Module Resolution
In Bun's runtime, when using `require`, if the target module is an ESM, it returns a module namespace object, similar to how it works in Node.js. Conversely, if the target is a CJS module, it returns the `module.exports` object. This dual support allows developers to gradually migrate their codebases from CJS to ESM without needing to rewrite everything at once[3].
Conclusion
While Bun facilitates the use of both module types together effectively, it does not provide automatic transpilation from CJS to ESM. Developers can leverage Bun's capabilities to work with both formats in a single project, making it easier to transition towards ESM as the ecosystem evolves[2][3].
Citations:[1] https://gist.github.com/jimmywarting/327a647942014d8ac4f4a333c351f94c
[2] https://bun.sh/blog/commonjs-is-not-going-away
[3] https://bun.sh/docs/runtime/modules
[4] https://blog.logrocket.com/transpile-es-modules-with-webpack-node-js/
[5] https://github.com/evanw/esbuild/issues/2417
[6] https://www.reddit.com/r/node/comments/zurr8b/how_often_is_esm_actually_used_compared_to/
[7] https://www.youtube.com/watch?v=odnYzaVtVlM
[8] https://stackoverflow.com/questions/74937600/how-to-support-es-modules-and-commonjs-modules-at-the-same-time