如何将全局样式添加到angular 6/7库
我试图以与在角度应用程序中相同的方式添加全局样式,但是这完全不起作用。
I was trying to add global styles in the same way like in angular app, but it totally does not work.
我的库的名称是 example-lib ,所以我添加了 styles.css
到 / projects / example-lib /
。我在主要 angular.json
文件中添加了样式:
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构建示例库
错误:
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?
我对此有一种解决方法。只需创建没有视图封装的库的根组件,然后所有样式就会变为全局。
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';
现在您的 my-library.component.scss 和核心.scss 是全局的
styles / core.scss
body {
background: #333;
}
core.scss 是可选的,我喜欢保持根文件干净。
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.