一、CSS相较于Styuls的缺点
| 方面 | CSS 缺点(vs Stylus) |
|---|---|
| 变量 | 仅运行时变量,功能受限 |
| 嵌套 | 不支持,代码冗长 |
| 复用机制 | 无 mixin、函数 |
| 运算 | 依赖 calc(),能力有限 |
| 控制流 | 无条件、循环 |
| 模块化 | @import 性能差,无真正模块系统 |
| 开发效率 | 重复代码多,维护成本高 |
- 这是你项目中的
CSS代码
.container {
display: flex;
width: 90vw;
}
.container .panel {
height: 80vh;
border-radius: 50px;
color: #fff;
cursor: pointer;
flex: 0.5;
margin: 10px;
position: relative;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
transition: all 700ms ease-in;
}
.container .panel h3 {
font-size: 24px;
position: absolute;
left: 20px;
bottom: 20px;
margin: 0;
opacity: 0;
transition: opacity 300ms ease-in 400ms;
}
.container .panel.active {
flex: 5;
}
.container .panel.active h3 {
opacity: 1;
}
- 这里有很多重复的选择器
- 大括号和标点符号的使用使嵌套关系很困难
😱 这些都会大大影响我们的开发效率
二、Stylus就是来解决这些问题的
tylus 是一个富有表现力、动态且功能强大的 CSS 预处理器,支持简洁的语法、变量、 混合(mixin)、函数和嵌套规则,可编译为标准 CSS
- 这是使用Stylus写的样式
.container
display flex
width 90vw
.panel
height 80vh
border-radius 50px
color #fff
cursor pointer
flex 0.5
margin 10px
position relative
background-size cover
background-position center
background-repeat no-repeat
transition all 700ms ease-in
h3
font-size 24px
position absolute
left 20px
bottom 20px
margin 0
opacity 0
transition opacity 300ms ease-in 400ms
&.active
flex 5
h3
opacity 1
✅是不是比CSS简洁很多,而且 便于看懂
- ⚠️虽然 Stylus 比 CSS方便,但它仍然只是预处理器,
- 而我们的浏览器在渲染样式时只认CSS,所以就需要我们将其编译为CSS文件
三、怎么编译呢?
-
- 全局安装
在文件命令界面输入:npm i -g stylus
-
- 编译脚本
先创建 style.styl文件,在写完样式之后,在文件命令界面输入:stylus style.styl -o style.css
💡这样你就会发现会多了一个CSS文件
-
- 边写边编译
- 如果写样式之后,有多次修改,那么编译脚本的次数很多😢
这当然没问题 命令界面输入 :stylus style.styl -o style.css -w
这样你写一行代码,他就会帮你把对应的样式补充在之前创建的CSS文件中🚀
结语
- 🎉OK,你已经可以更高效开发了快去试试吧!