What is the difference between `main` and `module` vs `exports` in package.json?

Viewed 520

I'm trying to write a library that can be both required and imported.'ve found different approaches online, which are as follows:

{
  "main": "mylib-cjs.js",
  "module": "mylib-esm.js"
}

and

{
  "exports": {
    "import": "mylib-esm.js",
    "require": "mylib-cjs.js"
  }
}

What are the pros and the cons of both approaches, and how do they differ?

1 Answers

I think you should not use module anymore. It works in webpack and some other bundling tools, but it does not work in node.js. It's older way of defining an ESM entry point. So if you are writing purely an FE library, you are fine using module, but in node.js you need to use the exports. Only that one will work correctly when running in type: module mode.

Not sure about bundlers and their support for exports, but I would expect them to get in line with node's entry point.

Related