Keeping CSS out of JS in Angular 2/Angular-CLI Keeping CSS out of JS in Angular 2/Angular-CLI typescript typescript

Keeping CSS out of JS in Angular 2/Angular-CLI


This is the whole point of encapsulated components.

A component should have it's own styles encapsulated with it so it can be shipped with the styles.

Imagine you want to publish one of your components to be used by others, shouldn't it have its own styles with it ?

That means Angular needs a way to link those css to the component , thus seperates them into chunks and injects them into head tag.

To solve your problem though , you have couple of options :

1- Not using the Emulated Encapsulation :

Components by default have a property called encapsulation which is set to Emulated , you need to change it to None:

@Component({   encapsulation:ViewEncapsulation.None})

Then , you can put all you css in the head tag your self like you'd do with a normal html page.

2- If the problem is theme ing , you can make your component themeable .

You can have a theme attribute for your component and then based on that change the styleing :

@Component({   selector:'my-component',   styles:[    `       :host{          [theme="blue"]{              change what ever you want :               h1{                color:blue;               }           }       }    `  ]})

And then , using this component would be like :

  <my-component [attr.theme]='"blue"'></my-component> // would be blue theme  <my-component></my-component> // would be default


Go to your base Html file(where the root module, main app is injected) and link the CSS stylesheets in your header section.

Webpack will not include it in it's compiled/combined css file which is injected into the page. The css file will still be included at run time in the browser.

<html><head>  <base href="/">  <meta charset="utf-8">  <title>dummy</title>  <meta name="viewport" content="width=device-width">//was not injected/modified by webpack  <link rel="apple-touch-icon" sizes="57x57" href="app/images/apple-icon-57x57.png">//webpack's injected this below from other components's imported/inline css rules<link href="index-c2cacb5fa3dfbca6116f4e4e63d5c3c7.css" rel="stylesheet"></head>


With angular-cli 1.6.5 you can do this:

ng serve --extract-css

You will still have the style-encapsulation features, but devtools will now point to the component css source file.