如何为不同编译器分别设置 includePaths?

解读

面试官抛出此题,核心想验证两件事:

  1. 你是否真的在多编译器共存(Sass/LESS/Stylus/PostCSS)的项目里实操过 Gulp,而不是只会跑单一场景的 demo;
  2. 你是否理解 Gulp 的流式管道隔离原则——同一条流里混用多个编译器时,如何防止配置互相污染。
    国内大厂的前端工程往往要兼容老项目(node-sass)+ 新模块(dart-sass),还要给 UI 框架(Ant Design、TDesign)单独指定主题变量目录,includePaths 配错一行就会导致「找不到 @import」的编译失败,面试时直接决定你“能不能上手干活”。

知识点

  • Vinyl 文件对象:Gulp 流里每份文件都携带 path、base、cwd 等元信息,includePaths 只对当前管道生效,不会写回文件系统。
  • 编译器插件的签名差异:gulp-sass 使用 sass.compiler 属性,gulp-less 使用 paths 属性,gulp-stylus 使用 include 属性,拼写一旦写错就会被静默忽略。
  • Node 路径解析规则:includePaths 必须是绝对路径数组,相对路径会以 process.cwd() 为基准,在 monorepo 里极易踩坑。
  • 流隔离技巧:使用 gulp-if 或 gulp-filter 把文件拆成多条子流,分别传入不同编译器,避免「一条流走到底」导致配置串扰。
  • 缓存与增量编译:国内项目 10W+ 行 Sass 很常见,配合 gulp-cached + gulp-progeny 时,includePaths 变化必须触发缓存失效,否则调试时会出现「改完变量没生效」的假死现象。

答案

  1. 先抽离「路径常量」,保证多人协作时路径一致:
const { src, dest, parallel } = require('gulp');
const sass = require('gulp-sass')(require('sass')); // dart-sass
const less = require('gulp-less');
const path = require('path');

const ROOT = process.cwd();
const INCLUDE_SASS = [path.resolve(ROOT, 'src/styles/variables')];
const INCLUDE_LESS = [path.resolve(ROOT, 'node_modules/antd/lib/style')];
  1. 为 Sass 与 LESS 分别创建独立任务,各自传入对应的 includePaths:
function buildSass() {
  return src('src/**/*.scss', { sourcemaps: true })
    .pipe(sass({ includePaths: INCLUDE_SASS }).on('error', sass.logError))
    .pipe(dest('dist/css', { sourcemaps: '.' }));
}

function buildLess() {
  return src('src/**/*.less', { sourcemaps: true })
    .pipe(less({ paths: INCLUDE_LESS })) // less 插件用 paths 字段
    .pipe(dest('dist/css', { sourcemaps: '.' }));
}

exports.styles = parallel(buildSass, buildLess);
  1. 若文件混在同一目录,用 gulp-if 做流内分流,保证 includePaths 不串台:
const gulpif = require('gulp-if');

function isSass(f) { return f.extname === '.scss'; }
function isLess(f) { return f.extname === '.less'; }

function mixedStream() {
  return src('src/**/*.{scss,less}')
    .pipe(gulpif(isSass, sass({ includePaths: INCLUDE_SASS })))
    .pipe(gulpif(isLess, less({ paths: INCLUDE_LESS })))
    .pipe(dest('dist/css'));
}
  1. 最后加一层路径变化监听,includePaths 数组里的任何目录被改动时触发全量重编,防止缓存导致变量失效:
const watch = require('gulp-watch');
function devWatch() {
  watch(['src/**/*.{scss,less}', ...INCLUDE_SASS, ...INCLUDE_LESS], 
    { ignoreInitial: false }, 
    exports.styles
  );
}
exports.default = devWatch;

拓展思考

  • monorepo 场景:如果 includePaths 需要跨 package 引用,用 require.resolve('~@company/theme') 拿到真实目录,避免写 ../../../ 这种相对迷宫。
  • CI 提速:在 GitHub Actions 或阿里云的 Flow 流水线里,把 includePaths 目录打 tar 缓存,key 用 hashFiles('**/variables/**/*.scss'),能节省 30~50 s 的 node_modules 漂移时间。
  • Vite 混合迁移:国内很多团队逐步把 Gulp 迁到 Vite,但老项目仍用 Gulp 做遗留打包。可以在 Vite 配置里用 css.preprocessorOptions.scss.includePaths 复用同一份路径常量,实现「双轨构建」零配置差异。
  • 安全红线:includePaths 里千万别把 / 或 node_modules 全局根目录直接写进去,否则恶意 @import '/etc/passwd' 会把系统文件编译进产物,渗透测试会直接挂红。