如何编写自定义 PostCSS 插件并在 Gulp 中热重载?

解读

面试官抛出这道题,核心意图是验证候选人三点能力:

  1. 对 PostCSS 插件体系与 AST 操作是否真正“写过”而非“看过”;
  2. 能否把插件无缝嫁接到 Gulp 的流式管道,并解决国内项目常见的“文件缓存、路径别名、中文注释”等坑;
  3. 是否具备热重载闭环思维:文件变动 → 插件重新执行 → 浏览器无刷新更新,且内存占用低、速度快,在 10 人以上的前端团队里可落地。

如果仅回答“用 gulp-postcss 调用插件”而忽略本地开发阶段的热重载细节,会被判定为“只懂拼装,不懂工程化”。

知识点

  1. PostCSS 插件协议:
    • 必须导出一个接收 opts 的函数,返回 { postcssPlugin: string, Rule|Decl|AtRule(node, helpers) };
    • 通过 node.selector、node.value 读写 AST,用 result.warn() 抛出中文友好提示。
  2. Vinyl 流与缓存:
    • Gulp 4 默认启用 gulp.lastRun(),但自定义插件若内部异步未正确调用 callback(),会导致增量编译失效;
    • 国内项目常把 node_modules 放在 ../ 外层,需用 require.resolve 避免插件被重复安装。
  3. 热重载链路:
    • browser-sync + gulp.watch 双进程模型,禁用 GhostMode 滚动同步以减少大屏调试干扰;
    • 对 PostCSS 插件自身代码变动,使用 gulp-plumber 捕获语法错误,结合 nodemon 重启子进程,保证插件热更新不重启全量 Gulp。
  4. 性能红线:
    • 插件必须返回 Promise 或调用 callback,否则 Gulp 会报 “Did you forget to signal async completion?”;
    • 在 process.env.CI 环境下跳过 sourcemap 生成,节约 GitLab Runner 时间。

答案

  1. 初始化

    npm i -D postcss gulp-postcss browser-sync gulp-plumber nodemon
    
  2. 编写自定义插件 lib/postcss-px2vw.js(国内常用需求:px→vw 并兼容 750 设计稿)

    const plugin = (opts = {}) => {
      const { viewportWidth = 750, unitPrecision = 5 } = opts;
      return {
        postcssPlugin: 'postcss-px2vw',
        Declaration(decl) {
          if (!decl.value.includes('px')) return;
          const pxVal = parseFloat(decl.value);
          if (isNaN(pxVal)) return;
          const vwVal = (pxVal / viewportWidth * 100).toFixed(unitPrecision);
          decl.value = decl.value.replace(pxVal + 'px', vwVal + 'vw');
        }
      };
    };
    module.exports = plugin;
    module.exports.postcss = true;
    
  3. 在 gulpfile.js 中注册任务

    const { src, dest, watch, series } = require('gulp');
    const postcss = require('gulp-postcss');
    const bs = require('browser-sync').create();
    const plumber = require('gulp-plumber');
    
    function css() {
      return src('src/css/**/*.scss', { since: lastRun(css) })
        .pipe(plumber({ errorHandler: err => bs.notify(err.message, 5000) }))
        .pipe(sass())
        .pipe(postcss([
          require('./lib/postcss-px2vw')({ viewportWidth: 750 }),
          require('autoprefixer')
        ]))
        .pipe(dest('dist/css'))
        .pipe(bs.stream({ match: '**/*.css' }));
    }
    
    function serve(done) {
      bs.init({
        server: { baseDir: ['./dist', './src'] },
        ghostMode: false,
        notify: false
      });
      watch('src/css/**/*', css);
      // 插件自身变动重启子进程
      watch('lib/postcss-*.js', () => {
        bs.exit();
        require('nodemon')({ script: 'gulp', args: ['serve'] });
      });
      done();
    }
    
    exports.serve = series(css, serve);
    
  4. 运行

    npx gulp serve
    

    修改任何 .scss 或 postcss-px2vw.js,浏览器 200ms 内无刷新更新,终端无 “forget to signal async” 报错,即达标。

拓展思考

  1. 如果团队使用 Vite + monorepo,如何把上述 PostCSS 插件抽成独立包,并通过 workspace: 协议链接,保证本地开发时插件改动即时生效?
  2. 在 Webpack 5 模块联邦 场景下,PostCSS 插件需要返回 result.messages 供上层收集依赖,如何改造才能兼容 Gulp 与 Webpack 双构建?
  3. 当项目部署到 国内阿里云函数计算,构建环节运行在 512 M 内存容器,如何给插件增加 cache: true 选项,利用 /tmp 目录做跨构建缓存,避免每次冷启动重新全量编译?