我正在尝试使用sass的@extend
,以免将标记和html混在一起。如this article中所述。
简而言之,而不是写作
<div class="alert alert-primary>This is an alert!</div>
您可以改写类似
<div class="banner">This is an alert!</div>
.banner {
@extend .alert;
@extend .alert-primary;
}
样式和内容保持很好的分隔。
问题:当将其与webpack( sass-loader )和组件(例如 Vue.js 或Angular)一起使用时,我会运行出现了一个问题,其中包括引导程序部分,现在将导致整个引导程序文件完全编译为css。
对于使用部分.btn[data-v-3614b62c]
的每个组件以及该部分中定义的所有类的组件,这将导致一个类.btn[data-v-45ac961c]
和另一个bootstrap/scss/_buttons.scss
等。
即使我不使用它。
从长远来看,这对应用程序是有害的,因为它的大小会迅速增加,而且我认为浏览器会因为要解析的css类太多而变慢。
问题:我如何确保sass不复制整个导入的部分? 我可以在仅包含我使用的类的地方启用某种树状摇动吗? 我是否需要更改文件结构,以便sass理解我只需要部分类而不是所有类中的某些类?
代码示例
这是使用引导程序的vue组件
<template>
<form class="form">
<input type="text" class="input">
<button class="button-submit">Send</button>
<button class="button-cancel">Cancel</button>
</form>
</template>
<style lang="scss" scoped>
@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";
@import "node_modules/bootstrap/scss/root";
@import "node_modules/bootstrap/scss/buttons";
.form {
.button-submit {
@extend .btn;
@extend .btn-primary;
}
.button-cancel {
@extend .btn;
@extend .btn-danger;
}
}
</style>
这将导致整个部分_buttons.scss
编译成CSS,而不是仅编译成.form .button-submit
和.form .button-cancel
。
实时示例
https://codesandbox.io/embed/musing-feynman-8w2kx。
要查看我遇到的问题:
- 右键单击右侧的示例,然后单击“检查”
- 在“元素”标签中,导航到#document> html> head
- 在底部,您将有几个
style
元素 - 其中两个将包含所有按钮css,其中仅
[data-v-######]
属性是不同的,最后是我的几行代码。
请注意,生产版本也会发生同样的情况。然后,将CSS简单地捆绑在一个文件中,但是仍然存在重复项。