Ivan Mushketyk
Ivan Mushketyk

Reputation: 8285

TypeScript import from a nested folder in an external packabe

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/**/*"]
}

Upvotes: 3

Views: 1034

Answers (1)

Paleo
Paleo

Reputation: 23692

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": "."

Upvotes: 1

Related Questions