我们如何在跨组件的可重用性和共享样式的背景下设置 Web 组件的样式

How do we style webcomponents in the context of re-usability and sharing styles across components

我正在尝试制定一种策略,将品牌(样式)添加到 Web 组件(angular 在我的案例中是 2 个组件)。我想就可能存在相同组件的情况达成共识在页面上重复多次。想要在跨组件打包样式并将其抽象化时避免重复。当样式需要对组件具有原子性以及何时对其进行抽象以及我需要如何处理时,我该如何找到解决方案。非常感谢

根据我的经验,拥有多个处理特定区域的样式文件非常有用。在我的例子中,我调用了那些模板。这是我的主项目中 main.scss 文件的示例:

@import 'templates/menu.scss';
@import 'templates/forms.scss';
@import 'templates/pagination.scss';
@import 'templates/general.scss';
@import 'templates/type.scss';
@import 'templates/labels.scss';
@import 'templates/navbar.scss';
@import 'templates/sidebar.scss';
@import 'templates/buttons.scss';
@import 'templates/tables.scss';
@import 'templates/panels.scss';
@import 'templates/alerts.scss';
@import 'templates/loading.scss';
@import 'templates/calendar.scss';
@import 'templates/comment-input.scss';

我是按需创建的。这就像编写任何类型的可重用代码一样。当您或您团队中的某个人注意到要创建的内容已经存在时。最好从组件的样式中移除,放在范围更大的样式文件中。

我们在一个由 5 名开发人员组成的团队中,并且工作得非常好。组件的特定行为是独立的,但它们共享的行为可供任何组件使用。

Another approach that I've though about using is to only import the template files as another styleUrl in the component. This way I would guarantee even more the style encapsulation.

假设您有一个具有特定行为的组件,但您还希望它具有可用的 labels.scss。你会这样做:

@Component({
  selector: 'my-component',
  templateUrl: 'my-component.component.html'
  styleUrls: ['my-component.component.css', '../shared/styles/labels.css']
})

我真的很喜欢第二种方法,但是随着项目变得非常大,您在导入共享样式时可能需要处理一些讨厌的相对路径。

希望对您有所帮助。