You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用gulp-rename与gulp-uglify生成单个同路径min文件?

Fixing Infinite *.min.min.js Generation in Gulp

Hey there, I totally get the frustration of that endless loop creating nested .min suffixes! Let's break down why this is happening and how to fix it quickly.

The Root Cause

Your browserSync task is watching all .js files in ./src/js/—including the *.min.js files your scripts task just generates. Every time a new *.min.js is created, the watcher triggers the scripts task again, which then compresses that minified file and renames it to *.min.min.js, and so on forever.

3 Simple Fixes

1. Exclude Minified Files from Your Task's Source

Modify your scripts task to ignore existing *.min.js files when it runs. This way, even if the watcher triggers the task again, it won't process the already-minified files:

gulp.task('scripts', function() {
  return gulp.src('./src/js/*.js', { ignore: './src/js/*.min.js' }) // Add ignore rule here
    .pipe(uglify())
    .pipe(rename( {suffix: '.min'} ))
    .pipe(gulp.dest('./src/js/'))
    .pipe(browserSync.stream());
});

2. Restrict the Watcher to Non-Minified Files

Instead of watching all .js files, tell the watcher to ignore *.min.js files. This prevents the watcher from triggering the task when a minified file is created:

gulp.task('browserSync', function(){
  browserSync.init({
    server : {
      baseDir : './'
    }
  });
  // Add ignored rule to exclude min files
  gulp.watch('./src/js/*.js', { ignored: './src/js/*.min.js' }, gulp.series('scripts'));
});

3. (Best Practice) Separate Source and Output Directories

The cleanest long-term fix is to keep your unminified source files in one folder and output minified files to another. This eliminates any chance of the watcher picking up generated files:

// Updated scripts task: output to dist/js instead of src/js
gulp.task('scripts', function() {
  return gulp.src('./src/js/*.js')
    .pipe(uglify())
    .pipe(rename( {suffix: '.min'} ))
    .pipe(gulp.dest('./dist/js/')) // Output to dist folder
    .pipe(browserSync.stream());
});

// Updated watcher: only watch src/js files
gulp.task('browserSync', function(){
  browserSync.init({
    server : {
      baseDir : './'
    }
  });
  gulp.watch('./src/js/**.js', gulp.series('scripts'));
});

This approach keeps your source code clean and avoids any accidental overwrites or loops.

内容的提问来源于stack exchange,提问作者jricc russel

火山引擎 最新活动