Minify CSS and JS with Gulp
This script minimizes a single CSS file, ./static/main.css
relative to the gulpfile, and a single JavaScript file, ./static/main.js
relative to the gulpfile to ./static/main.min.css
and ./static/main.min.js
respectively. It also creates the .map
files to make development easier and handles CSS browser prefixing with Autoprefixer
Install the Gulp CLI globally:
npm install gulp-cli -g
Create a package manifest in the root of the project:
touch package.json
Add to that:
{
"devDependencies": {
"autoprefixer": "^10.4.19",
"gulp": "^5.0.0",
"gulp-minify": "^3.1.0",
"gulp-postcss": "^10.0.0",
"gulp-rename": "^2.0.0",
"gulp-sass": "^5.1.0",
"gulp-sourcemaps": "^3.0.0",
"postcss": "^8.4.38",
"postcss-scss": "^4.0.9",
"sass": "^1.75.0"
}
}
Install it:
npm install
Create a gulpfile in the root of the project:
touch gulpfile.js
Add to that:
'use strict';
const gulp = require( 'gulp' );
const autoprefixer = require( 'autoprefixer' )
const postcss = require( 'gulp-postcss' )
const sass = require( 'gulp-sass' )( require( 'sass' ) );
const sourcemaps = require( 'gulp-sourcemaps' )
const minify = require( 'gulp-minify' );
const rename = require( 'gulp-rename' );
const compressCSS = () => {
// point to the CSS file
return gulp.src( './static/main.css' )
.pipe( sourcemaps.init() )
.pipe( postcss( [ autoprefixer() ] ) )
// compress the CSS to reduce file size
.pipe( sass( { outputStyle: 'compressed' } ).on( 'error', sass.logError ) )
.pipe( rename( 'main.min.css' ) )
.pipe( sourcemaps.write( '.' ) ); // passing a path tells it to write to a separate .map file rather than embedding it in the compressed CSS file
.pipe( gulp.dest( './static' ) );
}
exports.compressCSS = compressCSS;
const minifyJS = () => {
return gulp.src( './static/main.js' )
.pipe( sourcemaps.init() )
.pipe(
minify( {
ext: '.min.js',
noSource: true
} )
)
.pipe( sourcemaps.write( '.' ) ); // passing a path tells it to write to a separate .map file rather than embedding it in the minified JS file
.pipe( gulp.dest( './static' ) );
}
exports.minifyJS = minifyJS;
exports.watch = () => {
gulp.watch( './assets/a/main.css', compressCSS );
gulp.watch( './assets/a/main.js', minifyJS );
};
const minimizeStaticAssets = ( cb ) => {
compressCSS();
minifyJS();
cb();
}
exports.default = minimizeStaticAssets;
For Autoprefixer, create a browserlist file in the root of the project:
touch .browserslistrc
Add to that:
# https://github.com/twbs/bootstrap/blob/v5.3.3/.browserslistrc
# https://github.com/browserslist/browserslist#readme
>= 0.5%
last 2 major versions
not dead
Chrome >= 60
Firefox >= 60
Firefox ESR
iOS >= 12
Safari >= 12
not Explorer <= 11
During development, gulp will recreate the compressed files every time the source is changed via the gulp watch
task. Run gulp
alone to run the default action and recreate the compressed files once, or run each task independently as gulp compressCSS
or gulp minifyJS
.
Feedback?
Email us at enquiries@kinsa.cc.