Recently I’ve been working on a large Angular project with deeply nested folders and all the import paths were referenced relatively and they looked like this:
import { HelloWorldComponent } from '../../../../shared/components/hello-world/hello-world.component';
This imports are too long, hard to maintain and very annoying in large projects. Just imagine how much work is needed to update each path when moving a file that is referenced in 50+ locations (find and replace is not a solution here 🙂 ).
The good news is that TypeScript can be configured to use custom namespaces to point to specific paths by changing two compiler options inside tsconfig.json
file:
baseUrl
– base directory to resolve non-relative module names.paths
– list of mapping entries for module names to locations relative to thebaseUrl
Here is the default content for tsconfig.json
with two paths configured:
{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "paths": { "@scb/*": ["src/app/*"], "@scb-shared/*": ["src/shared/*"], } ... } }
With this setting, the long import given as an example, will turn into:
import { HelloWorldComponent } from '@scb-shared/components/hello-world/hello-world.component';
I’ve ended up changing all the imports to absolute imports in the project I was writing about, it was a tedious work but it saved me a lot of pain for the rest of the time spent on that project. It’s great to be able to move files around and not to bother about updating paths everywhere.
Let me know if you like this productivity tip 🙂 .
Hi, this is great, thanks! However I cannot make it work with webpack + ts-loader, it complains “module not found” for every module imported like that. Any tip?
And immediately after posting my question, I found the answer: 🙂
https://webpack.js.org/configuration/resolve
Hope it may help others!