Importing files in node package without including dist folder name

Viewed 2641

I have following directory structure for a library which will be imported by other node js project.

my-lib/
├─ dist/
│  ├─ index.js
│  ├─ foo.js
├─ src/
│  ├─ index.ts
│  ├─ foo.ts
├─ package.json

I have following package.json

{
  "name": "my-lib",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js"
}

I have specified main as dist/index.js, so if I understand correctly, members exported from index.ts (js) can be imported as import abc from 'my-lib'. If I have to access exported members from foo.ts (js) file then I might end up doing import foo from 'my-lib/dist/foo'. So here I have to specify the dist folder name in import path. Is there way to specify just 'my-lib/foo' omitting dist folder name? (just like importing dist/index.js file.)

2 Answers

This can be accomplished with subpath exports in package.json.

  "main": "./dist/index.js",
  "exports": {
    ".": "./dist/index.js",
    "./foo": "./dist/foo.js"
  }

As explained in node.js documentation, it is possible to add subpath exports. Check it out here.

In your case it should look similar to following

{
  "name": "my-lib",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/index.js",
  "exports": {
    ".": "./dist/index.js",
    "./foo": "./dist/foo.js"
  }
}

After exporting like this you can import as follows

import foo from 'my-lib/foo'
Related