Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the output folder from the import statements for my package users?

I have a Typescript-based project with multiple .d.ts files that I want to export as npm package and use in another project.

In that other project, I want to be able to call:

import {Foo} from "@my-company/project-name/x/y/Foo"

My project structure looks like:

<project_root>
|_ node_modules
|_ src
|  |_ x
|     |_ y
|     |  |_ Foo.ts
|     |_ Bar.ts
|_ package.json
|_ tsconfig.json

My tsconfig.json file:

{
  "compilerOptions": {
    "module": "es2015",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "declaration": true
  },
  "lib": ["es2015"],
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules"
  ]
}

The result of running tsc is that a dist folder is created containing the d.ts files and the .js files. When running npm pack, I end up with a .tgz file containing the following structure.

Note that it includes the dist folder in the directory structure.

package
 |_ dist
 |  |_...
 |_ package.json

The result is that I can't write

import {Foo} from "@my-company/project-name/x/y/Foo"

but have to write

import {Foo} from "@my-company/project-name/dist/x/y/Foo"

instead (note the extra dist in the path).

Based on the node documentation, I thought I could fix this by adding the following to my package.json file:

  "exports": {
    "./": "./dist/"
  }

but that seems to have no effect at all. The import cannot be found, unless I add the extra dist to the path.

I found a lot of other posts all with:

  • Solutions that look very complicated or are tied to a specific build system
  • Solutions that enforce special steps on the users of my package (like using compiler options)
  • Solutions/suggestions in closed Github issues (closed != fixed)
  • Old (over 2 internet years) posts, probably from before the exports option was available.

I would prefer to simply get that exports option to work. Anybody any idea what I am missing in my setup or doing wrong ? I am very new to the whole JS/TS/npm ecosystem so I think I might be overlooking something that is obvious to veterans.

For now, the workaround I found is to manually re-create the tgz file and remove the dist folder from the folder structure. But that feels far from perfect. For example npm install link_to_git_repo won't work.

like image 938
Robin Avatar asked Nov 30 '25 02:11

Robin


1 Answers

Configuring the typesVersions in the package.json fix this problem for me :

  "exports": {
    "./": "./dist/"
  },
  "typesVersions": {
    "*": {
      "*": ["./dist/*"]
    }
  },
like image 137
jbdemonte Avatar answered Dec 02 '25 21:12

jbdemonte



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!