Noticed these dots ('../') to access upper modules?
The problem we have here is that the deeper your project tree is the more '../' are required to access modules in higher layers. Actually, this doesn't look very beautiful to be honest. Fortunately we can change that.
The solution: path aliases
In TypeScript you can avoid these "bad" looking imports with the help of path aliases. With path aliases you can declare aliases that map to a certain absolute path in your application.
Let's get into it and setup some path aliases. Note that I won't explain how to setup a TypeScript project in Node.js. I assume that you did this already.
Now, you can use the new path aliases for module imports in your application. There occur any errors in your IDE (in my case VSC) or when you compile the code.
However, we are not done yet. When you try compile the TS code into JS you won't see any errors. But as soon as you run your compiled JS code you will get an error:
For example:
Error: Cannot find module '@modules/user'
Enter fullscreen modeExit fullscreen mode
Note that 'dist' is the folder where the compiled JS files are located.
Last but not least we have to register the path aliases in our application.
Add the following line at the top of your startup file:
I've just released a new package Alias HQ, which allows you to reuse your js/tsconfig.json path aliases in Webpack, Jest, Rollup, or any other library.
Just call hq.get('<library name>') in the config file you want to use aliases in, and you're done:
Had an issue with zeit/pkg because the generated files (in the dist folder) still had the @/dir/to/your/file references, which pkg could not handle.
In case you need to change your js files from the @/your-file back into their ../../../your-file form, you can use ef-tspm to bring it back. Note, if you do so, you won't need to deal with the extra steps for the module-alias specified above. Trade-off is you have an additional build step. So first you would tsc to build the typescript code, then ef-tspm to properly remove the module aliases.
These aliases -- which I've grown used to on the frontend frameworks which use webpack -- are a VERY welcome addition to writing typescript on the backend (or in other library code). My one question comes down to testing. I have a library with hundreds of tests but right now none of them run because I'm using Mocha/Chai with ts-node and I'm not sure but I think that ts-node is not able to use the alias.