Optimize imports with aliases in Angular


Difficulty

If there is one thing that creates clutter in an application, it is the very long imports of files into others in Angular components.
The typescript provides a convenient way to convert relative paths to absolute paths, acting on the tsconfig.json file.
This can be done by adding the paths of which you want to introduce an alias into the compilerOptions. We will use the @ as a shorthand to keep up with the standards.

  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/app/*"],
      "@users/*": ["src/app/users/*"],
      "~/*": ["src/*"]
    },
    ...
  }


If the application on which we are going to act has existed for some time and has more modules, you could run into the error of trying to insert the @ to prefix our path. That way, you’d end up with a module not found error.

You have to be careful because maybe the model we need is in a child folder of the parent module. In my case, I have inserted the user module with its components and then I will create an additional shorthand to also import the components of the child module without relative paths.

In this way it is possible to import any file with an absolute path and our shortcut.

import {CONSTANTS} from '@/Constants';


For complex applications, it is advisable to insert centralized styles for the variables and functions that can be imported. You can insert them into the individual components, if necessary.
To make life easier we can act on the angular.json configuration, inserting the option: stylePreprocessorOptions under the path:
projects.{myProject}.architect.build.options.stylePreprocessorOptions
at the same height as the configurations on the styles.

"styles": [
  "src/styles.scss"
],
"stylePreprocessorOptions": {
  "includePaths": [
    "src/styles"
  ]
},
...


This is the result. We can import our variables into any scss file simply by entering its name.


That’s all.
Good optimizations!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.