cssnode.jsgulpminifygulp-clean-css

How to use gulp-clean-css to write a new -min.css file instead of the default of overwriting the existing css source file?


How to use gulp-clean-css to write a new -min.css file instead of the default of overwriting the existing CSS source file?

Currently, I have this line which minifies the file. However, it overwrites the original with the minified version. I would like it to create a new file with the -min.css extension at the end of the original file basename.

src(filePath).pipe(minifyCSS()).pipe(dest('./css/'));

I know there is a gulp-copy in the npm repo I could use. I would like to know if there are any other ways to do it.

Thanks


Solution

  • I don't believe this is possible without installing any additional npm packages, though considering the nature of NodeJS, I don't think it would be considered unreasonable to require one.

    One possible way to achieve this (without gulp-copy) would be with gulp-rename and the rename command:

    gulp.src(config.css)
    
        // Output the file before cleaning
        .pipe(gulp.dest(config.css))
    
        // Clean the file
        .pipe(cleanCss())
    
        // Rename with a .min suffix (e.g. app.css -> app.min.css)
        .pipe(rename({ suffix: ".min" }))
    
        // Output the minified CSS file
        .pipe(gulp.dest(config.css));
    

    This will produce two files - the unminified original .css file and the minified .min.css file.