setup npm package with module alias is failing after build

177 Views Asked by At

I am trying to build my project and create an npm package, the built package will be stored in the dist directory, and am using module-alias but the resulting type declarations from the build are not resolving correctly, by showing the following error after installing my package in another npm project.

dist/index.d.ts: dist/index.d.ts

Importing in other projects doesn't resolve the types.

import {
  // no hint is showed - acessing the node_modules/project-example shows errors on the index exports
} from 'project-example'

I have the following typescript project structure:



├── jest.config.js
├── package.json
├── README.md
├── tsconfig.json
└── yarn.lock
├── src
│   ├── config.ts
│   ├── index.ts
│   └── moduleA
│       └── file.ts
--------------------

My package.json

{
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "rimraf ./dist && tsc"
  },
  "dependencies": {
    "@types/node": "18.14.2",
    "module-alias": "^2.2.3",
    "rimraf": "^5.0.1"
  },
  "devDependencies": {
    "@types/module-alias": "^2.0.2",
    "typescript": "^4.9.5"
  },
  "_moduleAliases": {
    "@/*": "dist"
  }
}

My config.ts file:

import path from 'path';
import moduleAlias from 'module-alias';
moduleAlias.addAlias('@', path.resolve(__dirname));

My index.ts file:

import './config'
export * from '@/moduleA/file'

My file.ts file:

export type Bar = {
  value: string
}

export function foo (): Bar {
  return {value: 'bar'}
}

After building my dist looks like this:

dist
├── config.d.ts
├── config.js
├── config.js.map
├── index.d.ts
├── index.js
├── index.js.map
└── moduleA
    ├── file.d.ts
    ├── file.js
    └── file.js.map

obs: running node dist/index.js works fine.

0

There are 0 best solutions below