How to add global style to angular 6/7 library How to add global style to angular 6/7 library angular angular

How to add global style to angular 6/7 library


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.


As @codeepic already pointed out, there is currently a standard solution.

In ng-package.json add

"assets": ["./styles/**/*.css"]

The provided paths should be the paths to your files. At the same time, they will be the paths inside your /dist folder.
On build, the files will be copied to /dist. Users of your library will be able to add them to their global styles as follows.

/* styles.css */@import url('node_modules/<your-library-name>/styles/<file-name>');

This way you can copy any type of files.

P.S. When used with CSS, do not forget that you can create an index.css file that can be imported just like node_modules/<your-library-name>/styles.


From Compiling css in new Angular 6 libraries:

  1. install some devDependencies in our library in order to bundle the css:

    • ng-packagr
    • scss-bundle
    • ts-node
  2. Create css-bundle.ts:

    import { relative } from 'path';import { Bundler } from 'scss-bundle';import { writeFile } from 'fs-extra';/** Bundles all SCSS files into a single file */async function bundleScss() {  const { found, bundledContent, imports } = await new Bundler()    .Bundle('./src/_theme.scss', ['./src/**/*.scss']);  if (imports) {    const cwd = process.cwd();    const filesNotFound = imports      .filter(x => !x.found)      .map(x => relative(cwd, x.filePath));    if (filesNotFound.length) {      console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);      throw new Error('One or more SCSS imports failed');    }  }  if (found) {    await writeFile('./dist/_theme.scss', bundledContent);  }}bundleScss();
  3. Add _theme.scss inside the /src directory of the library that actually contains and imports all the css that we want to bundle.

  4. Add postbuild npm script to run the css-bundle.ts

  5. Include it in the styles tag in your Application in the angular.json