Learn how to improve long relative import paths in a large Angular application. 306 words.
Last Updated
The purpose of this snippet is to show how to improve imports of TypeScript modules and Sass classes while we work on slightly larger Angular apps.
The nested paths headache
Imports for feature modules and SCSS style sheets can be a pain point when working in large enterprise Angular applications . See the imports below 😬:
import { SeoService } from '../../../../core/seo.service.ts';
import { PostsService } from '../../../services/posts.service.ts';
//...
@import "../../../../theme/fonts";
@import "../../../../theme/breadcrumb";
Does not look good! This can become a problem if you change the file location because you will have to rewrite each path that references this module or the scss class.
Solving the problem 💪
Typescript
Typescript provides a great way to solve this kind of problems allowing us to customize a single global namespaces for our Feature Modules. To eliminate long relative paths let’s add some options to our tsconfig.json
located on root of our Angular app:
baseUrl
- Setting baseUrl informs the compiler where to find modules.- Add
path
settings insideCompilerOptions
- It will be an object which keys are path aliases that you will be able to use in your code, and the values are arrays of paths the alias will be resolved to.
{
"CompilerOptions": {
"baseUrl": "src",
"paths": {
"@core/*": ["app/core/*"]
"@services/*": ["app/services/*"]
}
}
# ...
}
- Applying Nested Path Correction
import { SeoService } from '@core/seo.service.ts';
import { PostsService } from '@services/posts.service.ts';
//...
Sass
To solve scss classes imports, let’s add options to our angular.json
:
//... (ommited)
"styles": [
"src/styles.scss"
],
"stylePreprocessorOptions": { //👈 include this!
"includePaths": [
"styles/theme"
]
},
And with that simple change, our Sass code will now look like this:
@import "fonts";
@import "breadcrumb";