Stylus 转 CSS 是将 Stylus 文件(.styl)编译成标准的 CSS 文件(.css)的过程。Stylus 是一种 CSS 预处理器,它允许你使用更灵活的语法(如变量、嵌套、混合宏等)。在开发过程中,Stylus 文件需要通过编译器将其转换为浏览器可以理解的普通 CSS。
1. 如何将 Stylus 转换为 CSS
  要将 Stylus 文件转为 CSS,你需要使用 Stylus 编译器。Stylus 提供了命令行工具,用于将 .styl 文件编译为 .css 文件。以下是基本的步骤:
安装 Stylus 编译器
  首先,确保你已经安装了 Node.js 和 npm。然后,使用 npm 来安装 Stylus 编译器:
bash
npm install -g stylus
  如果你只想在某个项目中使用 Stylus 编译器,可以在项目中作为开发依赖安装:
bash
npm install --save-dev stylus
  编译 Stylus 文件
  使用命令行将 .styl 文件编译为 .css 文件。
bash
stylus input.styl -o output.css
  此命令会将 input.styl 文件编译为 output.css 文件。-o 标志表示输出文件的路径。
实时编译(监听文件变化)
  你还可以使用 --watch 标志来监听文件变化,并在 Stylus 文件更新时自动编译:
bash
stylus input.styl -o output.css --watch
  这样,每次你修改 input.styl 文件时,Stylus 会自动编译成最新的 output.css。
编译多个文件
  如果你有多个 Stylus 文件需要编译,你可以一次性将多个文件编译成 CSS 文件:
bash
stylus file1.styl file2.styl -o output.css
  或者使用通配符(*)来编译多个文件:
bash
stylus *.styl -o output.css
  压缩输出 CSS
  你可以使用 --compress 标志来压缩输出的 CSS 文件,去除空白字符、注释等,使其变得更加紧凑:
bash
stylus input.styl -o output.css --compress
  生成源映射(Source Map)
  如果你需要源映射,以便在调试时能查看原始 Stylus 代码,可以使用 --sourcemap 标志:
bash
stylus input.styl -o output.css --sourcemap
  这会为生成的 CSS 文件创建一个 .map 文件,帮助浏览器将编译后的 CSS 映射回源 Stylus 文件。
2. Stylus 文件的基本语法
  在将 Stylus 文件转换为 CSS 之前,了解一些 Stylus 的基本语法是很有帮助的。
变量
  Stylus 支持变量,允许你存储和复用样式中的常用值:
stylus
$primary-color = #3498db
  $font-size = 16px
body
  color: $primary-color
  font-size: $font-size
  混合宏(Mixins)
  Stylus 允许你定义混合宏,并在多个规则中复用它们:
stylus
border-radius(radius)
  -webkit-border-radius: radius
  -moz-border-radius: radius
  border-radius: radius
.button
  border-radius(5px)
  background-color: #3498db
  color: white
  嵌套
  Stylus 支持样式的嵌套,允许你清晰地表示层级结构:
stylus
.container
  width: 100%
  .header
  background-color: #f0f0f0
  color: #333
  运算
  Stylus 还支持数学运算,可以在样式中执行加法、减法、乘法等操作:
stylus
width = 100px
  padding = 10px
.container
  width: width + padding
  继承(@extend)
  Stylus 支持继承,可以让一个选择器继承另一个选择器的样式:
stylus
btn
  padding: 10px 15px
  border-radius: 5px
.primary-btn
  extends btn
  background-color: #007bff
  color: white
  3. Stylus 转 CSS 的示例
  假设你有一个简单的 Stylus 文件 styles.styl,内容如下:
stylus
// styles.styl
$primary-color = #3498db
  $font-size = 16px
body
  background-color: #f0f0f0
  font-family: Arial, sans-serif
  color: $primary-color
  font-size: $font-size
h1
  color: $primary-color
  font-size: 2em
  使用 Stylus 编译器将 styles.styl 转换为 styles.css,结果将是:
css
/* styles.css */
  body {
  background-color: #f0f0f0;
  font-family: Arial, sans-serif;
  color: #3498db;
  font-size: 16px;
  }
h1 {
  color: #3498db;
  font-size: 2em;
  }