Stylus 插件系统 #

插件概述 #

Stylus 插件可以扩展 Stylus 的功能,提供额外的混入、函数和特性。

安装插件 #

bash
# 安装插件
npm install nib --save-dev
npm install autoprefixer-stylus --save-dev
npm install rupture --save-dev

使用插件 #

bash
# 命令行
stylus -u nib main.styl

# Node.js API
stylus(str)
  .use(require('nib')())
  .render(...)

常用插件 #

1. Nib #

Nib 是最流行的 Stylus 插件库,提供大量实用的混入和函数。

bash
npm install nib --save-dev
stylus
// 使用 nib
@import 'nib'

// 渐变
.button
  background linear-gradient(top, #fff, #000)

// 清除浮动
.container
  clearfix()

// 透明度
.element
  opacity 0.5

// 边框圆角
.box
  border-radius 5px

// 阴影
.card
  box-shadow 0 2px 10px rgba(0, 0, 0, 0.1)

// 过渡
.element
  transition all 0.3s ease

// 变换
.element
  transform rotate(45deg)

2. Autoprefixer Stylus #

自动添加浏览器前缀。

bash
npm install autoprefixer-stylus --save-dev
javascript
// 使用
const stylus = require('stylus');
const autoprefixer = require('autoprefixer-stylus');

stylus(str)
  .use(autoprefixer())
  .render(...);
stylus
// 自动添加前缀
.element
  display flex
  transition all 0.3s
  transform rotate(45deg)
  user-select none

// 编译结果
.element {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

3. Rupture #

简洁的媒体查询语法。

bash
npm install rupture --save-dev
javascript
// 使用
const stylus = require('stylus');
const rupture = require('rupture');

stylus(str)
  .use(rupture())
  .render(...);
stylus
// 断点设置
rupture.enable-em-breakpoints = true
rupture.base-font-size = 16px

// 使用 rupture
.container
  width 100%
  
  +above(768px)
    width 750px
    
  +below(480px)
    padding 10px

// 更多断点混入
.element
  +mobile()
    font-size 14px
    
  +tablet()
    font-size 16px
    
  +desktop()
    font-size 18px

// 断点范围
.element
  +between(400px, 800px)
    color red

4. Jeet #

网格系统插件。

bash
npm install jeet --save-dev
stylus
// 使用 jeet
@import 'jeet'

// 列布局
.container
  center(1200px)

.sidebar
  col(1/4)

.content
  col(3/4)

// 偏移
.element
  col(1/3, offset: 1/6)

// 嵌套
.parent
  col(1/2)
  
  .child
    col(1/2)

5. Axis #

功能丰富的样式库。

bash
npm install axis --save-dev
stylus
// 使用 axis
@import 'axis'

// 按钮
button(color = #3498db)
  background-color color
  border-radius 5px
  padding 10px 20px

// 表单样式
input
  input()
  border 1px solid #ddd

// 表格
table
  table()
  border-collapse collapse

// 动画
.element
  animation(fadeIn 0.5s)

6. Stylus Loader Options #

Webpack 中配置插件:

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.styl$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'stylus-loader',
            options: {
              stylusOptions: {
                use: [
                  require('nib')(),
                  require('rupture')(),
                  require('autoprefixer-stylus')()
                ],
                import: ['nib']
              }
            }
          }
        ]
      }
    ]
  }
};

自定义插件开发 #

基本结构 #

javascript
// my-plugin.js
function myPlugin() {
  return function(style) {
    // 定义函数
    style.define('my-function', function(param) {
      return param.val * 2;
    });
    
    // 定义混入
    style.define('my-mixin', function() {
      // 返回样式对象
    });
  };
}

module.exports = myPlugin;

定义函数 #

javascript
// custom-functions.js
function customFunctions() {
  return function(style) {
    // 简单函数
    style.define('double', function(value) {
      return value.val * 2;
    });
    
    // 带单位的函数
    style.define('px-to-rem', function(px, base) {
      base = base || 16;
      return {
        type: 'unit',
        val: px.val / base,
        string: (px.val / base) + 'rem'
      };
    });
    
    // 颜色函数
    style.define('adjust-hue', function(color, degrees) {
      // 返回调整后的颜色
    });
  };
}

module.exports = customFunctions;

使用自定义函数:

stylus
// 使用
.element
  width double(50px)        // 100px
  font-size px-to-rem(16)   // 1rem

定义全局变量 #

javascript
// global-variables.js
function globalVariables() {
  return function(style) {
    style.define('theme-primary', '#3498db');
    style.define('theme-secondary', '#2ecc71');
    style.define('base-spacing', '16px');
  };
}

module.exports = globalVariables;

使用:

stylus
.button
  background-color theme-primary
  padding base-spacing

定义混入 #

javascript
// custom-mixins.js
function customMixins() {
  return function(style) {
    style.define('responsive-font', function(min, max, minVw, maxVw) {
      // 返回样式块
      return {
        type: 'block',
        nodes: [
          {
            type: 'property',
            name: 'font-size',
            value: min.val + min.string
          }
        ]
      };
    });
  };
}

module.exports = customMixins;

完整插件示例 #

javascript
// grid-plugin.js
function gridPlugin(options) {
  options = options || {};
  const columns = options.columns || 12;
  const gutter = options.gutter || '30px';
  const container = options.container || '1200px';

  return function(style) {
    // 定义变量
    style.define('grid-columns', columns);
    style.define('grid-gutter', gutter);
    style.define('grid-container', container);
    
    // 定义函数
    style.define('column-width', function(span) {
      const totalWidth = parseFloat(container) - (columns - 1) * parseFloat(gutter);
      const colWidth = totalWidth / columns;
      return {
        type: 'unit',
        val: colWidth * span.val + (span.val - 1) * parseFloat(gutter),
        string: (colWidth * span.val + (span.val - 1) * parseFloat(gutter)) + 'px'
      };
    });
    
    // 定义百分比列宽函数
    style.define('column-percent', function(span) {
      return {
        type: 'unit',
        val: (span.val / columns) * 100,
        string: ((span.val / columns) * 100) + '%'
      };
    });
  };
}

module.exports = gridPlugin;

使用:

stylus
// 使用插件
.container
  max-width grid-container
  margin 0 auto

.col-6
  width column-percent(6)  // 50%

.col-4
  width column-percent(4)  // 33.33%

插件配置 #

命令行配置 #

bash
# 使用多个插件
stylus -u nib -u rupture main.styl

# 带选项
stylus -u autoprefixer-stylus --with "{ browsers: ['last 2 versions'] }" main.styl

Node.js 配置 #

javascript
const stylus = require('stylus');
const nib = require('nib');
const rupture = require('rupture');
const autoprefixer = require('autoprefixer-stylus');

stylus(str)
  .use(nib())
  .use(rupture())
  .use(autoprefixer({
    browsers: ['last 2 versions']
  }))
  .render((err, css) => {
    if (err) throw err;
    console.log(css);
  });

Gulp 配置 #

javascript
const gulp = require('gulp');
const stylus = require('gulp-stylus');
const nib = require('nib');
const autoprefixer = require('autoprefixer-stylus');

gulp.task('styles', () => {
  return gulp.src('src/styles/*.styl')
    .pipe(stylus({
      use: [
        nib(),
        autoprefixer()
      ]
    }))
    .pipe(gulp.dest('dist/css'));
});

Webpack 配置 #

javascript
module.exports = {
  module: {
    rules: [
      {
        test: /\.styl$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'stylus-loader',
            options: {
              stylusOptions: {
                use: [
                  require('nib')(),
                  require('rupture')()
                ]
              }
            }
          }
        ]
      }
    ]
  }
};

插件最佳实践 #

1. 按需加载 #

javascript
// 只加载需要的插件
const usePlugins = {
  nib: true,
  rupture: true,
  autoprefixer: process.env.NODE_ENV === 'production'
};

stylus(str)
  .use(usePlugins.nib ? nib() : noop)
  .use(usePlugins.rupture ? rupture() : noop)
  .use(usePlugins.autoprefixer ? autoprefixer() : noop)
  .render(...);

2. 封装插件配置 #

javascript
// stylus-plugins.js
const nib = require('nib');
const rupture = require('rupture');
const autoprefixer = require('autoprefixer-stylus');

module.exports = function() {
  return [
    nib(),
    rupture(),
    autoprefixer({
      browsers: ['last 2 versions', '> 1%']
    })
  ];
};

// 使用
const getPlugins = require('./stylus-plugins');

stylus(str)
  .use(getPlugins())
  .render(...);

3. 开发/生产环境区分 #

javascript
const isProduction = process.env.NODE_ENV === 'production';

const plugins = [
  require('nib')(),
  require('rupture')()
];

if (isProduction) {
  plugins.push(require('autoprefixer-stylus')());
  plugins.push(require('csso-stylus')());
}

stylus(str)
  .use(plugins)
  .render(...);

下一步 #

掌握插件系统后,继续学习 最佳实践 了解如何编写高质量的 Stylus 代码!

最后更新:2026-03-28