如何在Vue组件中用PostCSS避免@extend %placeholders重复输出?
Sass占位符无法合并选择器以缩减CSS体积问题
需求说明
我正在使用Vue和Sass开发组件库,希望通过Sass的%placeholders替代工具类,将样式声明完全脱离HTML结构。目标写法:
<button class="btn" /> <div class="modal" />
而非依赖工具类的写法:
<button class="btn flex-center" /> <div class="modal flex-center" />
复现步骤
- 安装依赖:
pnpm install - 执行构建:
pnpm build - 查看打包后样式:
cat dist/styles.css
技术栈
- Vue 3
- Vite 4
- Sass 1.58
- PostCSS 8.4
代码示例
BaseBox.vue
<template> <div class="box"></div> </template> <style lang="scss"> @use "../../styles/placeholders"; .box { @extend %flex-center; color: blue; } </style>
BaseButton.vue
<template> <button class="btn">Test</button> </template> <style lang="scss"> @use "../../styles/placeholders"; .btn { @extend %flex-center; color: yellow; } </style>
_placeholders.scss
%flex-center { display: flex; justify-content: center; align-items: center; }
期望输出
构建后dist/styles.css的理想结果:
.box, .btn { display: flex; justify-content: center; align-items: center; } .box { color: blue; } .btn { color: yellow; }
实际输出
实际打包生成的样式:
.btn { display: flex; justify-content: center; align-items: center; } .btn { color: yellow; } .box { display: flex; justify-content: center; align-items: center; } .box { color: blue; }
使用PostCSS+cssnano合并规则后,输出变为:
.btn { align-items: center; color: #ff0; display: flex; justify-content: center } .box { align-items: center; color: blue; display: flex; justify-content: center }
可见占位符并未实现选择器合并,无法达到缩减CSS体积的目的。
内容的提问来源于stack exchange,提问作者floroz
相关产品推荐
相关产品推荐

