'Unable to resolve modules specified in package.json's "exports" field

I'm working on a JS web application and am trying to use the exports field in a package.json file to clean up the import statements for my module.

Here's my directory structure:

--> my-package-folder
   --> src
      --> index.js
      --> color
         --> index.js
     --> ui
        --> index.js

I would like to be able to import the color and ui sub-folders like so:

import * from '@project/my-package/color'
import * from '@project/my-package/ui'

// Instead of...
// import * from '@project/my-package/src/color/index.js'
// import * from '@project/my-package/src/ui/index.js'

Here's a snippet from my package.json:

  "name": "@project/my-package",
  "version": "1.0.0",
  "main": "./src/index.js",
  "type": "module",
  "exports": {
    "./color": "./src/color/index.js",
    "./ui": "./src/ui/index.js"
  },

For some reason, I get a 'can't resolve' error when trying to import either the color of ui sub-folders:

Module not found: Error: Can't resolve '@project/my-package/color'

The code that imports my-package is still able to import @project/my-package, which resolves to ./src/index.js (specified in the main field):

import * from '@project/my-package'    // This works

It's just importing the color and ui sub-folders that's a problem.

As a test (just to see what would happen), I removed the main field and instead placed its value in the exports field:

".": "./src/index.js"

I figured that if the exports field was being read in properly, then this change should still allow importing @project/my-package to work. But this actually caused @project/my-package to no longer be resolvable.

I noticed that quite a bit of documentation on the exports field is geared toward node.js applications. Since I'm not working on a node.js project, I'm wondering if that might have something to do with my issue. Maybe the exports field behaves differently when working in a browser.

Is there something else I'm missing? Currently, I'm running the application that's importing my-package locally using webpack-dev-server. Perhaps something in my webpack config file needs to be updated as well?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source