Search code examples
javascriptnode.jstypescriptnpm

Compiling typescript path aliases to relative paths for NPM publishing?


I have a typescript project that uses paths for imports. For example:

"paths": {
  "@example/*": ["./src/*"], 
}

Thus the project can import files directly from using statement like:

import { foo } from "@example/boo/foo";

For publishing to NPM I have I'm compiling the typescript files and then copying the result to a dist folder. Thus all the *.d.ts and corresponding *.js files are in the dist folder. I also copy package.json to the dist folder.

I now test this by generation a new typescript project and then run npm i -S ../example/dist, in order to install the project and attempt to run some of the compiled typescript code.

However the relative imports no longer work. For example if boo.ts depends on foo.ts it will say that it can't resolve foo.ts.

When I look at the *.d.ts files they contain the same paths that were used the source code before it was compiled. Is it possible to turn these into relative paths?

Update

I looks as if generating relative paths for Node is something Typescript does not perform automatically. If you would like this feature, as I would, please provide feedback on this bug report.


Solution

  • An update to how one can compile TS path aliases to relative paths.

    ttypescript(Transformer TypeScript)is a transformer framework that converts the TS path aliases to relative paths.

    Note ttypescript is deprecated and only works with TS below 5.0. Read more here - ttypescript

    If you have Typescript 5+, use ts-patch. Migrating from ttypescript is easy.

    You will need to install both ts-patch and typescript-transform-paths.

    npm i --save ts-patch typescript-transform-paths

    Then, in tsconfig.json under compilerOptions, add the property below:

    "plugins": [
      { "transform": "typescript-transform-paths" }
    ]
    

    Then update your build script to tspc. Read more here - ts-patch