Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/53377419/how-to-add-global-style-to-angular-6-7-library

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...