How to add global style to angular 6/7 library

Jaroslaw K. picture Jaroslaw K. · Nov 19, 2018 · Viewed 22.5k times · Source

I was trying to add global styles in the same way like in angular app, but it totally does not work.

My libraries' name is example-lib, so I added styles.css to /projects/example-lib/. I added styles in main angular.json file:

...
"example-lib": {
  "root": "projects/example-lib",
  "sourceRoot": "projects/example-lib/src",
  "projectType": "library",
  "prefix": "ngx",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-ng-packagr:build",
      "options": {
        "tsConfig": "projects/example-lib/tsconfig.lib.json",
        "project": "projects/example-lib/ng-package.json",
        "styles": [
          "projects/example-lib/styles.css" <!-- HERE 
        ],
      },
...

but when I tried build library using command:

ng build example-lib

I got error:

Schema validation failed with the following errors:
  Data path "" should NOT have additional properties(styles)

I guess that is the other way to add global styles in separate library. Anyone can help me?

Answer

Xpleria picture Xpleria · Mar 27, 2019

I have a workaround for this. Just create the root component of your library without view encapsulation and all its styles will be then global.

my-library.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'lib-my-library',
  templateUrl: './my-library.component.html',
  styleUrls: ['./my-library.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class MyLibraryComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

my-library.component.html

<!-- html content -->

my-library.component.scss

@import './styles/core.scss';

Now your my-library.component.scss and core.scss are global

styles/core.scss

body {
    background: #333;
}

core.scss is optional, I just like to keep the root files clean.


Update: In case you want your mixins and variables too, then follow this answer.