Alright, so you’ve decided to do something nice and shiny, and now you’re working on the JavaScript library, which is actually written with beloved TypeScript, aren’t you? Very well.
This article is written by our engineer Bogdan Birdie and originally published here.
The problem with paths
Let’s skip all the development steps and land when everything is already fine. Your polished code is working and well tested. All your components and helpers have types. The build is running green, and so index.d.ts
being generated as well. And… you use absolute imports paths for your own reason.
In our team, at Rolique, we prefer to use absolute paths in imports whenever we can, seemingly, always.
This is a questionable topic, so, please, consider the text below as my personal viewpoint.
Imports with absolute paths look way more cleaner, and we can move files inside of the project with no hesitation, without a need to update its imports.
All this is very handy and sweet until your library is being added to some project, and this is where the problem arises.
TypeScript can resolve the absolute paths inside of your library repo because you told exactly how. It would look into tsconfig.json
for the baseUrl
and would use that, well, as a base for that path.
Well, but there is no such thing as tsconfig.json
in your build
or dist
folder, isn’t it? Right, none. But the imports are still absolute.
Once your library will be added to any TypeScript project — none of the absolute imports would be resolved inside of the library, simply because it doesn’t know, where to look for the files you import.
Ok, fine. We can have relative paths for the root of the library, so it would resolve all of them, regardless of whether this is in your repo or in the context of another project that is using your library.
Well, gotcha!
The problem is fixed on the root level, but not completely. If some of the nested files use absolute import — it is the same story, it would not resolve.
Shall we give up here? NO! And many times NO!
CLI tsc-alias, to the rescue!
tsc-alias
is a tool that would replace all absolute imports with relative imports. For you. Automatically.
Ok, let’s go! Install the package:
yarn add tsc-alias -Dornpm install tsc-alias --save-dev
Then, we need to add the magic command to the package.json
scripts:
All good, now let’s create that tsconfig.aliases.json
file, which we will specifically use for the tool only, not to mess with the main config. For the sake of safety, we will actually extend the main config.
Now, run the script, and you are done, congratulations!
Summary
tsc-alias
is a neat tool for the job. Especially, when you don’t want or just can’t add any builder configs (Webpack, Rollup, etc). This was the case for me since the library has managed with create-react-library
boilerplate.
With this approach, you need just a tiny bit of work to get the job done. So why not consider it?
Thanks for reading this topic! Stay tuned and follow us!