9

My newest typescript project is split into different modules and submodules.

My file structure:

package.json
(...)
/src
| /module1
| | index.ts
| | (...)
| | /subModule1
| | | index.ts
| | | (...)
| | /subModule2
|   | index.ts
|   | (...)
| /module2
  | index.ts
  | (...)

Every (sub)module has a index.ts file holding the module's exports.

Now I finally want to publish my package. One should be able to import stuff from the modules in the following way:

import { A } from "package/module1";
import { B, C } from "package/module1/subModule2";

I've already used this syntax on importing stuff from other packages on npm. But I can't find any explanations on how to implement such behavior. I've found some article explaining it for multiple files, but not for multiple modules structured in folders and subfolders.

MeineHTMLCodes
  • 509
  • 5
  • 19

1 Answers1

5

See "Subpath exports" in Node documentation:

Example:

{
  "main": "./main.js",
  "exports": {
    ".": "./main.js",
    "./submodule": "./src/submodule.js"
  }
}

This article may help you with that:

Plus some TypeScript-specific info in this issue on GitHub:

And since you say that you've already used this syntax on importing stuff from other packages on npm, then you might also take a look at the source code of those packages to see how they do it.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • 4
    Thanks a lot :DD Your answer and [this package](https://github.com/teppeis/typescript-subpath-exports-workaround) solved the whole issue :) – MeineHTMLCodes Mar 29 '22 at 10:37
  • 1
    @MeineHTMLCodes Great to know that I could help and thanks for the link to this package :) – rsp Mar 30 '22 at 00:31
  • 1
    I also have this kind of structure but when I import the sub packages typescript doesn't seem to find its declarations. Is there any tip you guys have about that? – Cagri Uysal Jul 21 '22 at 08:49
  • This works, I mean, the loaded modules are available. But wit [this](https://devblogs.microsoft.com/typescript/announcing-typescript-4-7-rc/#package-json-exports-imports-and-self-referencing) syntax, TS(4.7.4) does not recognize it. EDIT: `tsconfig.json` > `"module": "Node16"` and `"moduleResolution": "Node16"` makes it work entirely – Omar Omeiri Aug 11 '22 at 21:34
  • Even with TS 5+ I can only get submodules to work using the `typesVersions` work around. I've tried the MS syntax referenced in the comment above and the examples in the "Support for NodeJS 12.7+" GitHub issue. Nothing other than `typesVersions` has any impact at all. – WillyC Mar 20 '23 at 18:54