The Problem - Super Long Import Statements
As you know, an Angular app’s file structure can be relatively deep, making it difficult to figure out where a module lives when importing it. The idea is to make your import paths go from ../../../../ to @namespace.
When you have a large Angular project with deeply nested files and folders it leads to import statements that look like this…
// import from component.ts
import { MyService } from '../../../../my.service';
// import from service.ts
import { HelloWorldComponent } from '../shared/deeply/nested/hello-world/
hello-world.component';
It’s might be fine occasionally, but it becomes difficult to maintain for each new component you build.
You can then point to any directory in your project and give it a custom namespace. Any name will work, but watch out for name collisions with existing node packages, i.e. @angular, @ngrx, etc. The end result looks like…
import { MyService } from '@services/my.service';
import { HelloWorldComponent } from '@components/hello-world.component';
Much nicer! And we never need to think about the relative file location of an import - a simple, yet powerful productivity booster.
We can make this possible by configuring TypeScript to use custom namespaces to point to specific paths.
// tsconfig.json in the root dir
{
"compileOnSave": false,
"compilerOptions": {
// omitted...
"baseUrl": "src",
"paths": {
"@services/*": ["app/path/to/services/*"],
"@components/*": ["app/somewhere/deeply/nested/*"],
"@environments/*": ["environments/*"]
}
}
}
For more info please refer this link
No comments:
Post a Comment