Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript package with multiple entry points

The standard way to expose node package modules is to list them in the index.ts, like so:

export * from './module1';
export * from './module2';

However, this loads the content of both modules immediately. I want to have a module that is not exported in the index.ts file, as it requires some optional dependencies to be installed.

I followed this guide: https://blog.mozilla.org/data/2021/04/07/this-week-in-glean-publishing-glean-js/

My package.json:

  "exports": {
    ".": {
      "import": "./dist/es/index.js",
      "require": "./dist/cjs/index.js"
    },
    "./module2": {
      "import": "./dist/es/module2.js",
      "require": "./dist/cjs/module2.js"
    }
  },
  "typesVersions": {
    "*": {
      ".": [
        "./dist/types/index.d.ts"
      ],
      "./module2": [
        "./dist/types/module2.d.ts"
      ]
    }
  },
// fallback for older Node versions:
  "module": "dist/es/index.js",
  "main": "dist/cjs/index.js",
  "types": "dist/types/index.d.ts",

After I build the project (with tsc, separately for CJS and ESM) the output dir structure looks like this:

- dist
  - cjs
    - index.js
    - module2.js
  - es
    - index.js
    - module2.js
  - types
    - index.d.ts
    - module2.d.ts

However, when I publish this package and install it in the client project, module2 does not work.

import {sayHello} from 'ts-exports-test';
import {sayGoodbye} from 'ts-exports-test/module2';

console.log(sayHello());
console.log(sayGoodbye());

I run it with ts-node and I'm getting the error:

src/index.ts:2:26 - error TS2307: Cannot find module 'ts-exports-test/module2' or its corresponding type declarations.

Note: with clients using TS 4.5 the types paths can be declared in "exports" section, making the "typesVersions" hack unnecessary. But this is for the future.

like image 888
Radzikowski Avatar asked Dec 05 '25 17:12

Radzikowski


1 Answers

It works if you define the paths in typesVersions like this:

  "typesVersions": {
    "*": {
      "*": [
        "dist/types/index.d.ts"
      ],
      "module2": [
        "dist/types/module2.d.ts"
      ]
    }
  }

Not sure what convention does it follows, but it looks like paths like . or ./ are not valid.

You can check the repo https://github.com/diedu89/ts-export-import-test

like image 85
diedu Avatar answered Dec 08 '25 08:12

diedu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!