What's the best way to publish npm package types without including /dist/ in the import path?

I’m having trouble with my npm package @mylib/core. I’ve set up my project with a src/ folder and I’m using TypeScript to build into a dist/ folder. The types are generating fine, but when I publish and try to use the package, the import paths include /dist/.

For example, I’m seeing imports like:

import { SomeType } from '@mylib/core/dist/utils'

But I want users to be able to import like this:

import { SomeType } from '@mylib/core/utils'

I’ve tried publishing from the dist/ folder directly, but then I can’t import anything at all. The editor shows only a few useless options when I try to import.

What’s the correct way to set up my package so that the types are included, but the /dist/ part isn’t in the import path? I’ve looked around but haven’t found a solution that works for my setup.

hey there, i’ve dealt with this before! try tweaking ur package.json. add a “typings” or “types” field pointing to ur main declaration file (usually index.d.ts) in the dist folder. also, make sure ur “main” field points to the right js file. that shud fix the import paths for ya!

I’ve been through this headache before, and I found a solution that works like a charm. The key is in your tsconfig.json file. Make sure you set ‘declarationDir’ to ‘./dist’ and ‘outDir’ to ‘./dist’ as well. Then, in your package.json, set ‘main’ to ‘./dist/index.js’ and ‘types’ to ‘./dist/index.d.ts’.

Here’s the kicker: create a “files” array in your package.json and include both ‘dist’ and your type declaration files. Something like:

{"files": ["dist", "*.d.ts"]}

This setup worked wonders for me. It keeps your source and built files separate, while allowing clean imports without the ‘/dist/’ in the path. Just remember to run your build script before publishing, and you should be good to go. It took me a while to figure this out, but it’s been smooth sailing since!

I’ve encountered this issue in my projects as well. One effective solution is to utilize the ‘exports’ field in your package.json. This allows you to define precise mappings for your package’s entry points. Here’s an example:

{
  "exports": {
    ".": "./dist/index.js",
    "./utils": "./dist/utils/index.js"
  }
}

This approach enables users to import from ‘@mylib/core’ or ‘@mylib/core/utils’ without exposing the ‘dist’ directory. It’s crucial to ensure your TypeScript configuration (tsconfig.json) is set up correctly, particularly the ‘declaration’ and ‘outDir’ options. This method has worked well for me in maintaining clean import paths while preserving type information.