【发布时间】:2017-06-15 15:27:46
【问题描述】:
一般问题
我想设置可重用 Angular 组件的样式以匹配特定客户端项目的样式。
我在一个单独的项目中维护可重用组件并从中生成一个 npm 包。该包发布到私有 NPM 存储库 (Sinopia),然后安装到多个客户端项目中。
一般样式 - 当然 - 特定于组件,但颜色和字体 - 例如 - 应该与客户端项目匹配。
如何最好地将客户端项目中定义的颜色和字体等样式应用于可重用组件?
当前实施
目前我正在使用https://github.com/jvandemo/generator-angular2-library 搭建可重用组件库。 它会生成一些 Gulp 任务,让我构建一个 dist 版本。 发布该 dist 并使用已发布的包可以正常工作,但构建的代码让我很难找出可行的主题策略。
Gulp 构建任务将在最终代码中内联 HTML 和 CSS 资源。
一个示例组件
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.scss'],
})
export class MessagesComponent {
constructor(private messagesService: MessagesService) {
}
}
在构建过程中“扁平化”
var MessagesComponent = (function () {
/**
* @param {?} messagesService
*/
function MessagesComponent(messagesService) {
this.messagesService = messagesService;
}
...
return MessagesComponent;
}());
MessagesComponent.decorators = [
{ type: Component, args: [{
selector: 'app-messages',
template: "<div *ngFor=\"let message of messages\"> <div class=\"message {{message.type}}-message\"> {{message.message}} <i class=\"fa fa-remove\" (click)=\"removeMessage(message)\">x</i> </div> </div>",
styles: [".message { line-height: 36px; padding: 4px 20px; margin: 2px; position: relative; } .message .fa-remove { position: absolute; right: 20px; cursor: pointer; } .info-message { background-color: #005CAB; color: white; } .error-message { background-color: red; color: white; } "],
},] },
];
MessagesComponent.decorators 现在包含内联样式。
具体问题
使用https://github.com/jvandemo/generator-angular2-library 生成器是创建组件库的好选择吗?还是有更好的方法?
如何“覆盖”我的颜色和字体样式 可重复使用的组件?
我曾希望能够在组件库中使用 scss 变量,这些变量可以在客户端项目中(重新)定义。类似的东西
可重用组件messages.component.scss:
.info-message {
background-color: $primary-color;
color: white;
}
客户项目/style/_style-vars.scss:
$primary-color: #005CAB;
关于如何解决这个问题的任何想法?
跟进
我又进了一步:
我现在使用 CSS3 变量,这让我快到了:
在可重用组件中,我定义我的 SCSS 变量如下:
$primary-color: var(--ang-ux-primary-color, #5FB0FD);
.ang-ux-primary {
background-color: $primary-color;
}
在我的客户项目中,我定义了这样的样式(style.scss):
// styling reusable components
:root {
--ang-ux-primary-color: #666666;
}
这可行,但似乎我不能在我的 CSS 变量的定义中使用 SCSS 变量:
$primary-color: #666666;
// styling reusable components
:root {
--ang-ux-primary-color: $primary-color;
}
导致可重用组件中的 $primary-color 为空。 我为这个问题打开了一个单独的线程:Using SCSS variable inside CSS3 variable definition not working?
【问题讨论】:
-
This walkthrough 展示了如何创建支持 Angular Material 主题的组件库。虽然它基于 Angular-cli,但可能仍然有用。
标签: angular themes shared-libraries styling reusability