gulp 的 watch 在监听文件时会略过一些文件
发布于 4 年前 作者 ruinb0w 2070 次浏览 来自 问答

问题: 我在添加或修改src中文件时,watch的add和change事件会忽略一些文件, 导致src变了dist没变. 是不是我的gulpfile有什么问题? (遗漏的文件即包括ts, scss也包括图片文件) 代码如下:

const {src, dest, watch} = require('gulp');
const clean = require('gulp-clean');
const sass = require('gulp-sass');
sass.compiler = require('node-sass');
const ts = require('gulp-typescript');
const rename = require('gulp-rename');

const path = require('path');

function watcher(){
  watch("./src/**/*")
    .on('add', handleAdd)
    .on('unlink', handleRemove)
    .on('change', handleChange)
}

function handleAdd(file){
  console.log('handle add', file);
  // 检查文件类型, ts和sass需要编译别的直接复制
  const ext = path.parse(file).ext;
  switch (ext) {
    // case '.js':
      // obfuscate(file);
      // break;
    case '.ts':
      compileTs(file);
      break;
    case '.scss':
      compileSass(file);
      break;
    default:
      cpFile(file);
  }
}

function handleRemove(file){
  // console.log('handle remove');
  // 将src中删除的文件从dist中删除
  const destPath = file.replace("src", "dist");
  return src(destPath, {read: false, allowEmpty: true})
  .pipe(clean());
}

function handleChange(file){
  // console.log('handle change');
  // 先删除后复制
  handleRemove(file);
  handleAdd(file);
}

function cpFile(file){
  // 将文件复制到dist对应的目录
  // console.log('run cp');
  const destPath = path.parse(file.replace("src", "dist")).dir;
  return src(file)
  .pipe(dest(destPath));
}

function compileSass(file){
  // console.log('run sass');
  const destPath = path.parse(file.replace("src", "dist")).dir;
  const name = path.parse(file).name;
  return src(file)
  .pipe(sass())
  .pipe(rename(`${name}.wxss`))
  .pipe(dest(destPath))
}

function compileTs(file){
  const destPath = path.parse(file.replace("src", "dist")).dir;
  return src(file)
  .pipe(ts({declaration: true}))
  .on('error', () => {})
  .pipe(dest(destPath))
}

exports.default = watcher;
3 回复

@i5ting 我在添加或修改src中文件时,watch的add和change事件会忽略一些文件, 导致src变了dist没变. 是不是我的gulpfile有什么问题?

@ruinb0w 如果是前端文件,用browsersync试试

回到顶部