How to correctly use exports and subpaths on package.json using TypeScript?

Viewed 92

It's my first time trying to create a npm package using TypeScript, and I've been experiencing some troubles, probably because I missunderstood something following the documentation. I'm using Node 16.16.0 with npm 8.13.2 at the moment of writing this.

First of all, my project structure looks like this.

src/
├─ module1/
│  ├─ index.ts
├─ module2/
│  ├─ index.ts
package.json
tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "esModuleInterop": true,
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

package.json

{
  "name": "@owner/mypackage",
  "version": "v1.0.0",
  ...
  "files": [
    "lib/**/*"
  ],
  "type": "module",
  "exports": {
    "./module1": "./lib/module1/index.js",
    "./module2": "./lib/module2/index.js",
    "./package.json": "./package.json"
  }
}

The thing is that, when publishing the module, it generates the following structure:

lib/
├─ module1/
│  ├─ index.js
├─ module2/
│  ├─ index.js
package.json

Leaving me with the following importing structure:

import {Foo} from "@owner/mypackage/lib/module1";

Instead of the desired one:

import {Foo} from "@owner/mypackage/module1";

How can I achieve that pattern? And, in case there is, can I improve it or follow better practices?

0 Answers
Related