Search code examples
reactjstypescripttypescript-typingstsconfigts-loader

Typescript declaration file created with alias instead of relative path


Edit 1: Added GitHub URL to project

Edit 2: Removing baseUrl from tsconfig.json fixes all problems and using relative imports works fine.

Link: Github

How do I generate a typescript declaration file with relative paths instead of alias?

I am creating a library(samplelibrary) in UMD mode and publishing it in npm. The packed npm library has only build folder(with typings), package.json and README.md

When I try to consume the library in another typescript app, the build fails due to invalid type declaration file which is being generated. The type declaration file contains alias instead of relative path.

Compilation log:

ERROR in /workspace/myproject/node_modules/samplelibrary/build/typings/src/foo.d.ts(403,17): TS2307: Cannot find module 'utils/bar

How to fix this problem?

Actually created declaration file foo.d.ts:

declare const Foo: {
   bar: typeof import("utils/bar");
}

Expected file:

declare const Foo: {
   bar: typeof import("./utils/bar");
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "sourceMap": true,
    "rootDir": "./",
    "baseUrl": "./src",
    "paths": {
      "@samplecompany/sampleproject": ["./"]
    },
    "outDir": "build",
    "removeComments": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "declaration": true,
    "declarationDir": "typings",
    "importHelpers": true
  },
  "files": ["types/untyped-modules.d.ts"],
  "include": [
    "src/**/*",
    "test/**/*",
    "build/**/*",
    "styleguide-renderer/**/*"
  ],
  "exclude": ["node_modules"]
}

Folder structure:

root
  -src
    -utils
       -bar.ts
    -foo.ts

utils/bar.ts

export const bar = {
   hello: "World"
}

src/foo.ts

import { bar } from "./utils/bar.ts

export default const Foo = {
    bar
};

Solution

  • To fix this issue,

    • Remove baseUrl usage from your typescript config.
    • Use only relative imports in your project like ../somefile, ./somefolder/file, etc.,

    Fixed here