Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript import from a nested folder in an external packabe

Tags:

typescript

I am working that will contain several independent folders like this:

/src
  /a
    ClassA1.ts
    ClassA2.ts
    index.ts   # Exports ClassA1 and ClassA2
  /b
    ClassB1.ts
    ClassB2.ts
    index.ts   # Exports ClassB1 and ClassB2

I want to create this package and publish it to npm (let's say it will be called my-package) and allow other projects import those projects like this:

import { ClassA1 } from 'my-package/a'
import { ClassB1 } from 'my-package/b'

I've figured out how to preserve a folder structure when compiling TypeScript code using tsconfig, so now the result of TypeScript compilation looks like this:

/dist
  /a
    ClassA1.d.ts
    ClassA2.d.ts
    index.d.ts
    ClassA1.js
    ClassA2.js
    index.js
  /b
    ClassB1.d.ts
    ClassB2.d.ts
    index.d.ts
    ClassB1.js
    ClassB2.js
    index.js

Unfortunately, when I publish this package the only way to import classes from this package is like this (notice the dist part of the path):

import { ClassA1 } from 'my-package/dist/a'

Which is different from how I want this to look like.

It seems that I am missing something simple, but I can't figure out how to fix the import path.

Here is my tsconfig.json:

{
  "compilerOptions": {
    "rootDir": "src",
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "declaration": true,
    "outDir": "./dist",
    "moduleResolution": "node"
  },
  "include": ["src/**/*"]
}
like image 740
Ivan Mushketyk Avatar asked Apr 11 '26 23:04

Ivan Mushketyk


1 Answers

NPM doesn't provide a way to configure something like a "module root directory" inside a NPM package. Therefore, the output directory must be the package directory:

"outDir": "."
like image 96
Paleo Avatar answered Apr 13 '26 21:04

Paleo



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!