Npm library developed with Typescript and module-alias

1k views Asked by At

I am developing an npm library using Typescript as programming language. To develop it comfortably, I used the paths option in tsconfig.json and module-alias so that I would have been able to write imports such as import * from '@/utils'. The problem is that these paths remain the same also in the transpiled js files. This should be good because module-alias should work with these paths. The problem is that it does only when I use it locally, but when I install the library with npm and try to run it, it stops to work. How can I solve this?

Note: I found the problem, if I put the __moduleAliases config in the package.json of the project using my library and use the path to my library's dist it works. Still I do not know how to solve this problem.

2

There are 2 answers

0
EuberDeveloper On BEST ANSWER

Turned out very ostic to solve. I eventually used webpack in order to change all the @ aliased paths to normal paths, so that this problem did not persist, and removed module-alias. I used this webpack plugin https://www.npmjs.com/package/tsconfig-paths-webpack-plugin, while this other plugin could be used without webpack https://www.npmjs.com/package/tsconfig-paths

To see a library compiled with webpack and using this plugin you can see https://github.com/euberdeveloper/euberlog

0
EuberDeveloper On

I think I found a solution, but it is still not perfect.

To module-alias I can pass as an argument the path to the package.json with the settings, so I just use moduleAlias(path.join(__dirname, '..', 'package.json')); to specify in an "absolute" way the package.json of my library and even if it is installed by another user in another project module alias will use the package.json of my library.

There are still two problems:

  • The first is that if the project importing my library uses module alias as well, it won't work anymore because it will search for aliases in my library and not in my project.
  • The second is that if my project uses typescript, errors are thrown when @ is encountered. I think that the only way to solve this is by using something that would change the '@' paths to the real paths in the js result