Improving long relative paths import

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 😬:

file_type_ng_component_ts post-details.component.ts
import { SeoService } from '../../../../core/seo.service.ts';
import { PostsService } from '../../../services/posts.service.ts';

//...

file_type_scss2 post-details.component.scss
@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 inside CompilerOptions - 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.

Be careful with name collisions, I recommend prefix everything with the name of your app.

default_file tsconfig.json
{
    "CompilerOptions": {
        "baseUrl": "src",
        "paths": {
            "@core/*": ["app/core/*"]
            "@services/*": ["app/services/*"]
        }
    }
    # ...
}

  • Applying Nested Path Correction

file_type_ng_component_ts post-details.component.ts
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:

default_file tsconfig.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:

file_type_scss2 post-details.component.scss
@import "fonts";
@import "breadcrumb";

Q&A Chat