Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 571
Ole Avatar asked Jul 16 '18 02:07

Ole


Video Answer


2 Answers

As a brief follow-up to arhnee's suggestion, it seems that as of Aug 2020, Microsoft still refuses to implement custom transformers for whatever reason, so these modules remain relevant.

So to future readers, here's how you can actually compile TS path aliases to relative paths. ttypescript is merely a transformer framework that requires a "path transformer" in order to actually convert the TS path aliases. Thus you will need to install both ttypescript and typescript-transform-paths.

npm i --save ttypescript typescript-transform-paths

Then, it's easy as just specifying usage by adding the following property to the compilerOptions object in tsconfig.json:

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

And finally, run ttsc instead of tsc.

like image 187
qiu Avatar answered Oct 05 '22 17:10

qiu


There is a project called ttypescript that you can use for this. If you use it with the module typescript-transform-paths I beleive it will acheive what you want.

like image 37
arhnee Avatar answered Oct 05 '22 18:10

arhnee