Exports fields and Webpack 4: It just doesn’t work
tl;dr
Webpack 4 does not support the exports field of imported packages. Take it as a sign you need to upgrade to webpack 5.
Module not found: Error: Can't resolve
This was the error I was getting when trying to import our new component library to an older Webpack 4 project. It was a confusing error because I could see the package in the node_modules folder, TypeScript was configured correctly, and I could import any other module from node_modules.
I started to catch on when I was able to isolate that is was only my module that was having issues. Then I remembered - we were using the relatively new exports
syntax to define how other modules could use it as a dependency.
Understanding the 'exports' field
let's first understand the purpose of the 'exports' field. Introduced as part of the Node.js module system, the 'exports' field allows package authors to specify alternative entry points for their modules. This feature offers flexibility, especially in scenarios where developers wish to expose specific functionalities without requiring users to import the entire package.
For instance, a package author could define multiple entry points in their package.json like so:
<code>{<br> "exports": {<br> "./entry1": "./src/entry1.js",<br> "./entry2": "./src/entry2.js"<br> }<br>}<br></code>
Here, 'entry1.js' and 'entry2.js' are exposed as separate entry points that consumers can import directly.
Gotta bite the bullet and upgrade
After a little searching I was able to determine that Webpack 4 didn't support the exports field in package.json. Bummer. Means I'd need to upgrade a whole bunch more dependencies, update the Webpack config in some cases, and just generally cause me more headaches.
Oh well, gotta do it anyway, might as well be now.