top of page

How to Create TypeScript Aliases?



Open your tsconfig.json file.


Set baseUrl value (under compilerOptions) as “src” instead of “.”


Add “paths” under compilerOptions.


Start to add your aliases with their path values relative to “src” folder.



You can replace an import to test in one of your ts files.



You will be getting an error for not being able to find imports so open your “tsconfig.json” file again. When its window is active, for Visual Studio Code Mac users, click “Command + Shift + P” and search for “restart ts server” (you may not see this command when an html file is open on your editor).



Click on it to restart TS server.


After that, you will see the import errors is gone and now it is time to add and replace aliases in your project.


For new imports, when you click to add missing imports, you will see that new imports will be added with aliases (you don’t need to replace paths each time you add a new import).



How to Add TypeScript Aliases to Your Angular Library Project

When you are working with a library project, things differ since now you will be working in a multi module project.


First of all, you will encounter into a tsconfig file problem if you are using Visual Studio Code:

VsCode automatically looks for a tsconfig.json file and it doesn't care about tsconfig.app.json, so paths needs to be specified in tsconfig.json.


For that reason, we will be editing our tsconfig.json file in the project’s main folder. Since we will have similar folder hierarchies in our libraries (such as model directory for model classes), it is possible to give multiple paths in your definition (you can see this link):



Don’t forget to restart your TS server after you save your changes. For Visual Studio Code Mac users, click “Command + Shift + P” and search for “restart ts server” (open a .ts file; you may not see this command when an html file is open on your editor).


Now you can replace your imports for “model” paths.





The Tech Platform

Comentarios


bottom of page