Home > Net >  How to split a typescript package into multiple submodules?
How to split a typescript package into multiple submodules?

Time:03-29

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.

CodePudding user response:

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.

  • Related