我试图以与在 Angular 应用程序中相同的方式添加全局样式,但是这完全不起作用。

我的库的名称是 example-lib ,因此我在styles.css中添加了/projects/example-lib/。我在主要angular.json文件中添加了样式:

...
"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
        ],
      },
...

但是当我尝试使用命令构建库时:
ng build example-lib
我收到错误消息:
Schema validation failed with the following errors:
  Data path "" should NOT have additional properties(styles)

我想这是在单独的库中添加全局样式的另一种方法。有人可以帮助我吗?

最佳答案

我对此有一种解决方法。只需创建您的库的根组件,而无需进行 View 封装,那么所有样式都会是全局的。

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';

现在,您的 my-library.component.scss core.scss 已全局

样式/core.scss
body {
    background: #333;
}

core.scss 是可选的,我只是想保持根文件干净。

更新:如果您也想要混合和变量,请遵循this answer

10-07 14:32
查看更多