DrillLab
第 12 / 105 道12 / 105 · #384

CSS 预处理器的优缺点

What is a CSS preprocessor? What are the advantages and disadvantages, if any, to using them over plain CSS?

先自己答,再往下看Answer it yourself first

一句话:预处理器是「用一种更强的语言写样式, 再编译成 CSS」。Sass / Less / Stylus 都是。

好处:变量集中管理、嵌套让结构清晰、 mixin 复用、能循环生成(比如 .mt-1.mt-10)、能拆成很多小文件再合并。

代价(面试重点问这半边):

  • 多一步构建。多一个依赖、多一份配置、 多一处可能出错的地方。
  • 嵌套太容易写深。一不注意就写出 .a .b .c .d span, 优先级越滚越高,最后只能靠!important 收场。这是预处理器最真实的坑—— 实践里一般限制自己不超过三层。
  • 调试要靠 source map。DevTools 里看到的是编译产物,行号对不上。
  • 门槛。新人得先学一套额外语法。

结论怎么说:「大项目、有设计系统、需要批量生成样式时值得; 小项目用原生 CSS 加自定义属性就够,因为它当年解决的两个主要问题(变量、嵌套) 原生已经支持了。」 —— 有取舍的回答比一味夸好。

In one line: a preprocessor lets you write styles in a more capable language and compiles them to CSS. Sass, Less and Stylus all qualify.

Upsides: variables in one place, nesting that makes structure obvious, mixins for reuse, loops that generate families of rules (.mt-1 through .mt-10), and splitting into many small files that get merged.

Costs — this is the half they probe:

  • An extra build step. One more dependency, one more config, one more place things break.
  • Nesting is far too easy to over-use. Before you notice you have written .a .b .c .d span, specificity keeps climbing, and the only way out is !important. This is the preprocessor’s most real trap — in practice teams cap themselves at about three levels.
  • Debugging needs source maps. DevTools shows you the compiled output and the line numbers do not match.
  • Onboarding cost. Newcomers must learn extra syntax.

How to land the conclusion: “Worth it on large projects with a design system and lots of generated styles; for small projects plain CSS plus custom properties is enough, because the two problems it originally solved — variables and nesting — are now native.” A weighed answer beats unconditional praise.