前言:从"玩具"到"生产"
上篇我们用 Stylus 快速构建了一个动画界面。
但要将其应用于企业级项目,我们还需要更强大的架构和更精细的优化。
本文将带你从"能用"迈向"精通",掌握 Stylus 的高阶玩法。
一、模块化架构:告别"面条式 CSS"
1. 目录结构
csharp
styles/
├── base.styl # 重置样式、变量
├── mixins.styl # 混合函数
├── layout.styl # 布局
├── components.styl # 组件
└── main.styl # 入口文件
2. 入口文件 main.styl
less
// 引入模块
@require './base'
@require './mixins'
@require './layout'
@require './components'
💡 使用
@require或@import组织代码,实现模块化。
二、Stylus 高级特性
1. 函数(Functions)
less
// 计算透明度
transparent(color, alpha)
unquote('rgba(' + red(color) + ',' + green(color) + ',' + blue(color) + ',' + alpha + ')')
.panel
background transparent(#000, 0.5)
2. 条件与循环
arduino
// 生成不同尺寸的按钮
for size in 12px 16px 20px
.btn-{size}
font-size size
生成:
css
.btn-12px { font-size: 12px; }
.btn-16px { font-size: 16px; }
.btn-20px { font-size: 20px; }
3. 作用域与命名空间
css
theme = {
primary: #007bff,
secondary: #6c757d
}
.btn
background theme.primary
三、性能优化:让 CSS 更轻更快
1. 减少选择器嵌套层级
避免:
css
.container
.wrapper
.panel
.content
.title
color red
推荐:
css
.panel-title
color red
嵌套过深影响渲染性能。
2. 合理使用 flex
- 避免在深层嵌套中滥用
flex。 - 复杂布局考虑
CSS Grid。
3. 压缩输出
编译时启用压缩:
lua
stylus style.styl -o style.min.css --compress
四、工程化集成
1. 与构建工具集成
Webpack 配置:
css
module.exports = {
module: {
rules: [
{
test: /.styl$/,
use: ['style-loader', 'css-loader', 'stylus-loader']
}
]
}
}
2. Source Map
css
stylus style.styl -o style.css --sourcemap
便于调试,定位到原始 .styl 文件。
五、Stylus vs Sass vs Less
| 特性 | Stylus | Sass | Less |
|---|---|---|---|
| 语法灵活性 | 极高(可省略 :、;) |
较高 | 一般 |
| 社区生态 | 中等 | 巨大 | 巨大 |
| 学习曲线 | 平缓 | 中等 | 中等 |
| 编译速度 | 快 | 中等 | 中等 |
💡 Stylus 更适合追求极致简洁和灵活性的开发者。
六、完整优化代码
scss
// base.styl
reset()
margin 0
padding 0
*
reset()
// mixins.styl
flex-center()
display flex
justify-content center
align-items center
// main.styl
@require './base'
@require './mixins'
body
flex-center()
height 100vh
overflow hidden
.container
display flex
width 90vw
.panel
height 80vh
border-radius 50px
color #fff
cursor pointer
flex 0.5
margin 10px
position relative
background cover center no-repeat
transition all 0.7s ease-in
h3
font-size 24px
position absolute
bottom 20px
left 20px
margin 0
opacity 0
transition opacity 0.7s ease-in 0.4s
&.active
flex 5
h3
opacity 1
@media (max-width: 480px)
.container
width 100vw
.panel:nth-of-type(4),
.panel:nth-of-type(5)
display none
结语:拥抱"编程式 CSS"
Stylus 不仅仅是一个工具,它代表了一种现代化的 CSS 开发范式 。
它让 CSS 从"样式表"进化为"样式程序",赋予开发者前所未有的控制力。