简体   繁体   中英

How to properly expose subpaths in package.json using the ”exports” key?

I've released a NPM package which is a plugin for a framework where only the main entry of my package.json is needed for usage in the framework and its environment. I also want to be able to use a subpath of the plugin in order for users to be able to use the plugin outside of this framework as well, which will require that the main entry point is never initialized as there are framework specific dependencies used there which I don't want to initialize when using this plugin outside of the framework.

My project structure looks like this:

.
├── index.js
├── submodule.js
└── package.json

Source code for the sake of this example looks like this:

// index.js
export default function () {
  return "foo";
}
// submodule.js
export default function () {
  return "bar";
}
// package.json
{
  "name": "my-package",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "exports": {
    ".": "./index.js",
    "./submodule": "./submodule.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "MIT"
}

According to Node.js documentation on this matter, this setup should allow me to use my package like this:

import myPackage from ’my-package’
import mySubModule from ’my-package/submodule’

In order to be able to test my package locally I run npm link in the project root of my npm package and then in another project i run npm link my-package . Now that I try to run the project (using parcel-bundler) that imports my-package and my-package/submodule like in the example above I get the following exception:

Cannot resolve dependency 'my-package/submodule'

I'm using NVM with Node v.12.18.4 and NPM v.7.15.0. I have also tried with Node v.14.17.0 but the issue persists. What am I missing?

It seems that the project setup is correct and that the problem lies in the parcel-bundler which does not support package.json#exports yet. There's currently an open issue on this matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM