简体   繁体   中英

How to make gulp-rename rename a concrete single file?

I generate CSS from LESS files and want to give to all generated Bootstrap CSS files a prefix "bootsrtap", but not to the bootstrap.css . So, I set the prefix directly after the compilation, but all my attempts to do a futher rename are failing.

var gulp = require('gulp'),
    less = require('gulp-less'),
    watch = require('gulp-watch'),
    prefix = require('gulp-autoprefixer'),
    plumber = require('gulp-plumber'),
    filter = require('gulp-filter'),
    rename = require('gulp-rename'),
    path = require('path')
;

// ...

gulp.task('build-vendors', function() {
    gulp.src(['./public/components/bootstrap/less/theme.less', './public/components/bootstrap/less/bootstrap.less']) // path to less file
        .pipe(plumber())
        .pipe(less())
        .pipe(rename({prefix: 'bootstrap-'}))
        .pipe(gulp.dest('./public/css')) // path to css directory
    ;
});

gulp.task('clean-up', function() {
    // const bootstrapFileRenameFilter = filter(['*', 'bootstrap-bootstrap.css']);    
    gulp.src('./public/css/bootstrap-bootstrap.css')
        .pipe(plumber())
        // .pipe(bootstrapFileRenameFilter)
        .pipe(rename({basename: 'bootstrap.css'}))
        .pipe(gulp.dest('./public/css'))
    ;
});

gulp.task('watch', function() {
    gulp.watch('public/less/*.less', ['build-less', 'build-vendors'])
});

// gulp.task('default', ['watch', 'build-less', 'build-vendors']);
gulp.task('default', ['build-less', 'build-vendors', 'clean-up']);

What I expect:

./public/css/bootstrap-theme.css
./public/css/bootstrap.css

What I'm currently getting:

./public/css/bootstrap-theme.css
./public/css/bootstrap-bootstrap.css

How to rename a single file from a.foo to b.bar ?

gulp-rename accepts a function as an argument to do the renaming. This allows you to target specific files for renaming using any criteria you like. In your case:

gulp.task('build-vendors', function() {
    gulp.src(['./public/components/bootstrap/less/theme.less',
              './public/components/bootstrap/less/bootstrap.less']) 
        .pipe(plumber())
        .pipe(less())
        .pipe(rename(function(path) {
            //rename all files except 'bootstrap.css'
            if (path.basename + path.extname !== 'bootstrap.css') {
                path.basename = 'bootstrap-' + path.basename;
            }
        }))
        .pipe(gulp.dest('./public/css'));
});

Since you now only rename those files where you actually want to have the bootstrap- prefix, you don't have to clean-up your mess afterwards and can just drop the whole clean task altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM