Make Angular 2+ imports sexier and make VSCode aware about it

Siddhartha Gupta
1 min readMay 2, 2018

--

Been working on angular 2 since its alpha stages. I loved most part of angular framework. But, one of issues which bugged me since the beginning is how we import files in it. You must have seen import hell ‘../../../’ while importing files through nested folder structure. Lets improve our typescript files import and get VSCode ready for the same(my favourite IDE).

Let’s get started by creating a new angular application

ng new improve-angular-imports

Create calculator service consisting a function ‘numSquare‘ which will take a number and returns back with the square of the number

Import calculator service into our simple app component

If you look at above code closely, you can see ‘../services/’ in our import path

import { CalculatorService } from '../services/calculator.service';

As the app grows these import urls become nested. After a period you start to loose track of your imports and it becomes a tedious task.

Solution

Open tsconfig.json(one at the root of angular project), and add the following code in ‘compilerOptions’

"baseUrl": "src","paths": {  "@service/*": ["app/services/*"]},

Change the Calculator service import in app.component.ts with following code:

import { CalculatorService } from '@service/calculator.service';

That’s it, done. Now instead of thinking ‘../../../’ while importing a service in your components simply use ‘@service’.

I hope you’ve enjoyed reading, complete source code is available at ‘GitHub’. Happy coding!

--

--

Siddhartha Gupta

Loves to talk about Frontend, Backend, Servers, Databases