I have developed several npm modules and compiled them in two ways:
- commonJS (using
exports.default =
) and - esm (using
export default
)
In my package.json, I have specified the main file as index.cjs.js
and the module file as index.esm.js
.
However, when I install the package and try to import it like this:
import myPackage from 'my-package'
It always chooses the main
file, not the module.
My question:
Is there a way to import the module
file instead of the main
file when doing
import myPackage from 'my-package'
in a JavaScript file?
Reason for setting commonJS file as "main":
I have observed that when working with Node, importing an esm
file using export default
is not feasible. Therefore, I have chosen the commonJS format for the "main"
path in package.json to make it accessible to a wider audience.
Explanantion for defining a separate "module" in package.json:
Many popular libraries like Vue.js follow this practice. More information can be found on this Stackoverflow thread:
What is the "module" package.json field for?
Reason for wanting to import the "module" file instead of the "main" file:
There is a known bug in Rollup where it does not correctly display JSDoc comments after importing a cjs
file, but it works fine with an es
file.
Avoiding the workaround:
One possible solution is to set "main" to the esm
file in package.json. However, this would prevent users utilizing my packages in Node apps from using it.
→I am somewhat perplexed by all of this, but after conducting thorough research, I believe I have a good understanding. If anyone has a better approach or any advice, please share it in the comments below!