Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 import shortcut

I'm developping an app using angular 2 and webpack. I was wondering, is there a way to make shortcuts for imports? What I mean is that I need sometimes to import components from folders that are up in the hierarchy so I end up doing something like this.

import { UserComponent } from '../../../models/users/user.ts';

Ideally just want to do:

import {UserComponent} from '@models/users/user.ts';

or something even shorter. Is there a way to create shortcuts?

thank you

like image 940
Miguel Rosales Avatar asked Feb 06 '23 07:02

Miguel Rosales


1 Answers

I know this question is many, many years old, and we have Angular 7, but in case someone has the same question, here's an answer.

You can configure path-mapping in the file tsconfig.json.

For example: Given that we have the following folder structure:

├── app
│   ├── app.component.html
│   ├── app.module.ts
│   ├── ...
│   └── shared
│       └── material
│           └── material.module.ts
...
...

I would like to add a "shortcut" the folder shared. Therefore I add "@shared/*": ["app/shared/*"] in the compilerOptions of the tsconfig.json file.

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@shared/*": ["app/shared/*"]
    },
   // ... and so on

Now I can Import my shared module like this:

import { MaterialModule } from '@shared/material/material.module';

Hope this helps someone.

Details can be found in the Typescript Documentation.

like image 58
BooFar Avatar answered Feb 13 '23 06:02

BooFar