I have css and js files in a directory (and subdirectories). I'm looking into different tools to compress the assets in all the directories. I'm trying to find a way to get gulp to compress all the files in those directories and save the compressed file in the same directory and name it with the following convention: [name].min.css or [name].min.js. So example.js would become example.min.js.
Is there a way to achieve this?
I've read the following on this:
http://gulpjs.com/plugins/
https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md
https://github.com/gulpjs/gulp/blob/master/docs/API.md
You usually don't want to generate the minified files in the same directory as the original files. You write all files that are generated by your build script to a single output directory. Some advantages of this approach are:
- Makes it easier to clean the build and recreate everything from scratch: you just delete that one output folder.
- You don't have to worry about generated files accidentally getting picked up by your build and getting processed again.
But since you asked, here's a solution that creates the minified files in the same directory as the original files. This creates a .min.css
and .min.js
file for every .css
and .js
file. All CSS files are assumed to be in a directory called css
(or its subdirectories) and all JS files are assumed to be in a directory called js
(or its subdirectories):
var gulp = require('gulp');
var rename = require('gulp-rename');
var cssnano = require('gulp-cssnano');
var uglify = require('gulp-uglify');
gulp.task('css', function () {
return gulp.src([
'css/**/*.css',
'!css/**/*.min.css',
])
.pipe(cssnano())
.pipe(rename(function(path) {
path.extname = ".min.css";
}))
.pipe(gulp.dest('css'));
});
gulp.task('js', function () {
return gulp.src([
'js/**/*.js',
'!js/**/*.min.js',
])
.pipe(uglify())
.pipe(rename(function(path) {
path.extname = ".min.js";
}))
.pipe(gulp.dest('js'));
});
gulp.task('default', ['css', 'js']);
Notice the negation pattern !css/**/*.min.css
that is used to prevent the already minified CSS from getting minified again on the next build. Same for the JavaScript.
I used gulp-cssnano and gulp-uglify to minify the CSS and JS, but there's plenty of other options out there that can act as drop-in replacements.