Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a typescript package into multiple submodules?

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.

like image 593
MeineHTMLCodes Avatar asked Mar 14 '26 11:03

MeineHTMLCodes


1 Answers

See "Subpath exports" in Node documentation:

  • https://nodejs.org/api/packages.html#subpath-exports

Example:

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

This article may help you with that:

  • Node.JS (New) Package.json Exports Field by Thomas Juster

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

  • Support for NodeJS 12.7+ package exports #33079

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.

like image 71
rsp Avatar answered Mar 17 '26 03:03

rsp