How to split a typescript package into multiple submodules?
Asked Answered
C

1

11

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.

Continuity answered 29/3, 2022 at 9:38 Comment(0)
S
9

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.

Salesin answered 29/3, 2022 at 9:55 Comment(7)
Thanks a lot :DD Your answer and this package solved the whole issue :)Continuity
@Continuity Great to know that I could help and thanks for the link to this package :)Salesin
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?Jonathanjonathon
This works, I mean, the loaded modules are available. But wit this syntax, TS(4.7.4) does not recognize it. EDIT: tsconfig.json > "module": "Node16" and "moduleResolution": "Node16" makes it work entirelyCry
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.Grith
@Continuity works perfectly thanks to rsp answer and the package you linked !Boathouse
It is working for me too, but auto-import doesn't work. I have to import manually. Otherwise it's as if types are invisible until I import them. Any idea why?Roam

© 2022 - 2024 — McMap. All rights reserved.