typescript npm package - how to not having to import from "dist/"

Viewed 3916

I am trying to build a utility npm package. In my src directory I have a bunch of typescript files that declare multiple interfaces / types. For example in src/value-updatable.ts I have:

export interface UnaryValueUpdatable<T> {
  value: T;
  onChange: (value: T) => void;
}

I compile my entire source to dist/, because it is a utility package there's no entry or main file, I just want to use the types in other projects. I am not even sure if compiling is necessary but the problem is still the same. When I install the package in a different project I have to import from the dist/ or src/ rather than from the package name itself.

For example:

import {UnaryValueUpdatable} from "my-utility-package/dist/UnaryValueUpdatable"

How do I have to configure my package to expose "pretty" paths like that: import {whatever} from "my-utility-package/whatever"?

package.json:

{
  "name": "my-utility-package",
  "version": "1.0.0",
  "files": [
    "dist/**/*"
  ],
  "scripts": {
    "build": "tsc"
  },
  "license": "MIT",
  "dependencies": {
    "typescript": "^3.6.4"
  }
}

tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "outDir": "dist",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "declaration": true,
    "jsx": "react"
  },
  "include": ["src"],
  "exclude": ["dist"]
}
1 Answers

You can create directories in your project root that contain package.jsonss that point to the directory you want to expose in your dist.

You can structure your project as:

package.json (for entire project)
src
 | secondary-package-name
   |- index.ts
secondary-package-name
 |- package.json (for secondary-module-name)
dist
 |- generated files

the package.json for your secondary module just needs to contain

{
  "name": "package/secondary-package-name",
  "private": true,
  "main": "../dist/secondary-package-name/index.js"
}

to point back to your dist

You should then be able to reference exports from the secondary package like so:

import { someFn } from "package/secondary-package-name"

provided it is exported from the index.ts file in that directory

You'll also need to make sure the files field of your main package.json includes the new directory:

"files": [
  "dist",
  "secondary-package-name"
],

(originally answered in https://stackoverflow.com/a/62482409/5574183)

Related