0
votes

I wanted to include prebuilt theme for angular app. I included below line in app.component.css.

@import "../../node_modules/@angular/material/prebuilt-themes/indigo-pink.css";

I was surprised it didn't apply the theme to my app. Then from docs I inferred I should include, now it works but I am curious why?

@import "@angular/material/prebuilt-themes/indigo-pink.css";

Inside common stylesheet, style.css not app.component.css! and the path (../../node_modules/@angular/material/prebuilt-themes/indigo-pink.css) makes more sense than "~@angular/material/prebuilt-themes/indigo-pink.css"

I have following questions,

1.What does it needs import only in style.css an why not inside appcomponent.css?

2.Though the path ~@angular/material/prebuilt-themes/indigo-pink.cs leads to nothing, how is the angular-material could pick the theme?

3.What does '~' mean in the above path?

To give more info, I have included project structure

enter image description here

1

1 Answers

2
votes

All the imports here are referenced relatively. It can be a hassle to remember how many folders to jump into and out of.

If you move your files around, you'll have to update all your import paths.

Let's look at how we can reference imports absolutely so that TypeScript always looks at the root /src folder when finding items.

Our goal for this will be to reference things like so:

import { HeaderComponent } from '@app/components/header/header.component';
import { FooterComponent } from '@app/components/footer/footer.component';
import { GifService } from '@app/core/services/gif.service';

This is similar to how Angular imports are referenced using @angular like @angular/core or @angular/router.

Setting Up Absolute Paths Since TypeScript is what is in charge of transpiling our Angular apps, we'll make sure to configure our paths in tsconfig.json.

In the tsconfig.json, we'll do two things by using two of the compiler options:

baseUrl: Set the base folder as /src paths: Tell TypeScript to look for @app in the /src/app folder baseUrl will be the base directory that is used to resolve non-relative module names. paths is an array of mapping entries for module names to locations relative to the baseUrl.

Here's the original tsconfig.json that comes with a new Angular CLI install. We'll add our two lines to compilerOptions.

{
  "compileOnSave": false,
  "compilerOptions": {
   ...

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

With that in our tsconfig.json, we can now reference items absolutely!

import { HeaderComponent } from '@app/components/header/header.component';
import { FooterComponent } from '@app/components/footer/footer.component';
import { GifService } from '@app/core/services/gif.service';

This is great because we can now move our files around and not have to worry about updating paths everywhere.

based on this:

/ - Site root
~/ - Root directory of the application

this can be useful too;