Minify css + Gulp - css

I have this gulpfile.js to compile css but I also want to minify my css. I try to run many different codes that I found in the internet but none of them works. Could any one help me? Thanks
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', gulp.series(function() {
return gulp.src(['scss/*.scss'])
.pipe(sass()) // converter o Sass em CSS
.pipe(gulp.dest('css'));
}));
gulp.task('watch', gulp.series(function() {
gulp.watch(['scss/*.scss'], gulp.parallel(['sass']));
}));
gulp.task('default', gulp.series(['sass', 'watch']));

Try This
i am sharing two function one for css and and another for sass
run this command
npm install gulp-concat gulp-autoprefixer gulp-sass gulp-sass-glob node-sass --save-dev
// and copy this code and set the
const { src, dest } = require("gulp");
const concat = require("gulp-concat");
const autoprefixer = require("gulp-autoprefixer");
const sass = require("gulp-sass");
const sassGlob = require("gulp-sass-glob");
sass.compiler = require("node-sass");
function css() {
return src("src/css/*.css")
.pipe(concat("style.css"))
.pipe(sassGlob())
.pipe(
sass({
outputStyle: "compressed" //expand or compact or compressed
}).on("error", sass.logError)
)
.pipe(
autoprefixer({
cascade: true
})
)
.pipe(dest("build/css/"));
}
function scss() {
return src('src/scss/style.scss') // import your all file in style.scss
.pipe(sassGlob())
.pipe(
sass({
outputStyle: 'compressed' // you can set "expand or compact or compressed" view
})
.on('error', sass.logError)
).pipe(
autoprefixer({
cascade: true
})
).pipe(dest('build/scss/'));
}
exports.css = css;
exports.scss= scss;

To fix your code try:
gulp.task('sass', function() {
return gulp.src(['scss/*.scss'])
.pipe(sass()) // converter o Sass em CSS
.pipe(gulp.dest('css'));
});
gulp.task('watch', function() {
gulp.watch(['scss/*.scss'], gulp.series('sass'));
});
gulp.task('default', gulp.series('sass', 'watch'));
But this form of functions is better:
// renamed since your plugin name is apparently `sass` as well
function sass2css() {
return gulp.src(['scss/*.scss'])
.pipe(sass()) // converter o Sass em CSS
.pipe(gulp.dest('css'));
};
function watch() {
gulp.watch(['scss/*.scss'], gulp.series(sass2css));
});
gulp.task('default', gulp.series(sass2css, watch));

Here is my gulp file it compiles and minifies css and js
(it also has some data for images and php files but they are unused)
var gulp = require('gulp'),
gutil = require('gulp-util'),
touch = require('gulp-touch-cmd'),
plugin = require('gulp-load-plugins')(),
merge = require('merge-stream');
// Select Foundation components, remove components project will not use
const SOURCE = {
scripts: [
// Place custom JS here, files will be concantonated, minified if ran with --production
'assets/scripts/**/*.js',
],
// Scss files will be concantonated, minified if ran with --production
styles: 'assets/style/scss/**/*.scss',
// Images placed here will be optimized
images: 'assets/images/src/**/*',
php: '**/*.php'
};
const ASSETS = {
styles: 'assets/style/',
stylesDist: 'assets/dist/style',
scripts: 'assets/scripts/',
scriptsDist: 'assets/dist/scripts',
images: 'assets/images/',
all: 'assets/dist/'
};
gulp.task('log', function() {
console.log(ASSETS.styles);
});
// Compile Sass, Autoprefix and minify
gulp.task('styles', function () {
var bulk = gulp.src(SOURCE.styles);
return merge(bulk)
.pipe(plugin.plumber(function (error) {
gutil.log(gutil.colors.red(error.message));
this.emit('end');
}))
.pipe(plugin.sourcemaps.init())
.pipe(plugin.sass())
.pipe(plugin.autoprefixer({
browsers: [
'last 2 versions',
'ie >= 9',
'ios >= 7'
],
cascade: false
}))
.pipe(plugin.cssnano({ safe: true, minifyFontValues: { removeQuotes: false } }))
.pipe(plugin.sourcemaps.write('.'))
.pipe(gulp.dest(ASSETS.stylesDist))
.pipe(touch());
});
// GULP FUNCTIONS
// JSHint, concat, and minify JavaScript
gulp.task('scripts', function () {
// Use a custom filter so we only lint custom JS
return gulp.src(SOURCE.scripts)
.pipe(plugin.plumber(function (error) {
gutil.log(gutil.colors.red(error.message));
this.emit('end');
}))
.pipe(plugin.sourcemaps.init())
.pipe(plugin.babel({
presets: ['es2015'],
compact: true,
ignore: ['what-input.js']
}))
.pipe(plugin.concat('scripts.js'))
.pipe(plugin.uglify())
.pipe(plugin.sourcemaps.write('.')) // Creates sourcemap for minified JS
.pipe(gulp.dest(ASSETS.scriptsDist))
.pipe(touch());
});
// Watch files for changes (without Browser-Sync)
gulp.task('watch', function () {
// Watch .scss files
gulp.watch(SOURCE.styles, gulp.parallel('styles'));
// Watch scripts files
gulp.watch(SOURCE.scripts, gulp.parallel('scripts'));
});
Here is another one i've used
// Initialize modules
// Importing specific gulp API functions lets us write them below as series() instead of gulp.series()
const { src, dest, watch, series, parallel } = require('gulp');
// Importing all the Gulp-related packages we want to use
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
var replace = require('gulp-replace');
// File paths
const files = {
scssPath: 'site/templates/styles/sass/**/*.scss',
jsPath: 'site/templates/scripts/**/*.js'
}
// Sass task: compiles the style.scss file into style.css
function scssTask(){
return src(files.scssPath)
.pipe(sourcemaps.init()) // initialize sourcemaps first
.pipe(sass()) // compile SCSS to CSS
.pipe(postcss([ autoprefixer(), cssnano() ])) // PostCSS plugins
.pipe(sourcemaps.write('.')) // write sourcemaps file in current directory
.pipe(dest('site/templates/dist')
); // put final CSS in site/templates/dist folder
}
// JS task: concatenates and uglifies JS files to script.js
function jsTask(){
return src([
files.jsPath
//,'!' + 'includes/js/jquery.min.js', // to exclude any specific files
])
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(dest('site/templates/dist')
);
}
// Cachebust
var cbString = new Date().getTime();
function cacheBustTask(){
return src(['index.html'])
.pipe(replace(/cb=\d+/g, 'cb=' + cbString))
.pipe(dest('.'));
}
// Watch task: watch SCSS and JS files for changes
// If any change, run scss and js tasks simultaneously
function watchTask(){
watch([files.scssPath, files.jsPath],
series(
parallel(scssTask, jsTask)
)
);
}
// Export the default Gulp task so it can be run
// Runs the scss and js tasks simultaneously
// then runs cacheBust, then watch task
exports.default = series(
parallel(scssTask, jsTask),
watchTask
);

Related

Gulp isn't running and I don't know why

I am using gulp in a wordpress theme and I keep getting this error about something not being a function inside the gulp-cli folder.
gulpInst.on('start', function(evt) {
^
TypeError: gulpInst.on is not a function
Here is my gulpfile.js
const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');
// SASS Task
function scssTask() {
return src(['assets/sass/*.scss', 'assets/sass/**/*.scss'], { sourcemaps: true })
.pipe(sass())
.pipe(postcss([cssnano()]))
.pipe(dest('assets/css', {sourcemaps: '.' }));
}
// JavaScript Task
function jsTask() {
return src('assets/js/*.js', { sourcemaps: true })
.pipe(terser())
.pipe(dest('dist/js', { sourcemaps: '.' }));
}
// Watch Task
function watchTask() {
watch('*.php');
watch(['assets/sass/**/*.scss', 'assets/js/*.js'], series(scssTask, jsTask));
}
// Default Gulp Task
exports.default = series(
scssTask,
jsTask,
watchTask
);
I have already tried uninstalling gulp and reinstalling it but nothing is fixing this error. Any idea how to fix this?

Gulp Watch starts but doesn't compile

When compiling my gulp file using "gulp watch", the gulp proces starts but doesn't compile. It isn't outputting any errors, so I'm not sure why it's starting but not compiling any of the files. This is what my gulp file currently looks like:
const gulp = require('gulp');
const stylus = require('gulp-stylus');
const nib = require('nib');
const rupture = require('rupture');
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
//const concat = require('gulp-concat');
// compiles styl to css and creates updates source map
gulp.task('styles', function(){
gulp.src('css/styl/style.styl')
.pipe(sourcemaps.init()) // <-- place sourcemaps.init before stylus nib pipe so that nib is included in sourcemap
.pipe(stylus({
use: [nib(),rupture()]
}))
.pipe(postcss([ autoprefixer() ]))
//.pipe(concat('style.css'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function(){
gulp.watch('css/**/*.styl', gulp.series('styles'));
});
As it is currently written it would compile on changes only, not on startup. What you want is to make your watch-task dependent on your styles task, so that styles is run before it starts watching. You can do this by passing another argument to gulp.task like this.
gulp.task('watch', ['styles'] function() {
gulp.watch('css/**/*.styl', gulp.series('styles'));
});

Running gulp commands one by one results in different output than running them in gulp.series. Why?

Below is my gulpfile. I am trying to generate minified css from scss and then rename it using gulp-rev. Running gulp clean:assets then gulp scss then gulp css works perfectly. But running gulp build does not do the task. The minified css gets stored in ./assets/css but the renamed css is not getting stored in ./public/assets
const gulp = require('gulp');
//gulp sass converts sass to css
const sass = require('gulp-sass');
//cssnano converts css to minified form
const cssnano = require('gulp-cssnano');
//rev renames the assets by appending content hash to filenames so that the browser treats it as a new asset if content is changed
const rev = require('gulp-rev');
const path = require('path');
const del = require('del');
gulp.task('clean:assets', function(done){
del.sync('./public/assets');
del.sync('./assets/css');
done();
});
gulp.task('scss', function(done){
gulp.src('./assets/scss/**/*.scss')
.pipe(sass())
.pipe(cssnano())
.pipe(gulp.dest('./assets/css'))
done();
});
gulp.task('css', function(done){
gulp.src('./assets/css/**/*.css', {base: path.join(process.cwd(), 'assets')})
.pipe(rev())
.pipe(gulp.dest('./public/assets/'))
.pipe(rev.manifest('public/assets/rev-manifest.json',{
base: process.cwd()+'./public/assets',
merge: true
}))
.pipe(gulp.dest('./public/assets'));
done();
});
gulp.task('build', gulp.series('clean:assets', 'scss', 'css'), function(done){
done();
})
gulp.task('scss', ()=> {
return new Promise((resolve, reject) => {
return gulp.src('./assets/scss/**/*.scss')
.pipe(sass())
.pipe(cssnano())
.pipe(gulp.dest('./assets/css'))
.on('end', resolve)
.on('error', reject);
});
});
Changed the scss task to above to get it working. Refer to https://stackoverflow.com/a/53937286/7374508

I am using gulp-autoprefixer and it doesn't work no matter what options I will choose

Everything is working correctly except autoprefixer. BrowserSync is reloading, in devTools lines are showen from sass files, but when I try to apply some flexbox, in my destination file main.css unfortunately there is no effect with autoprefixer. Could you please help me with that?
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
// compile scss into css
function style() {
// 1. where is my scss file
return gulp.src('./scss/**/*.scss')
// 2. pass that file through sass compiler & error log
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write())
.pipe(autoprefixer({browsers: ['last 2 version'], cascade: false})
// 3. where do I save the compiled CSS?
.pipe(gulp.dest('./css'))
// 4. stream changes to all browser
.pipe(browserSync.stream()))
}
function watch() {
browserSync.init({
server: {
baseDir: './'
}
});
gulp.watch('./scss/**/*.scss', style);
gulp.watch('./*.html').on('change', browserSync.reload);
gulp.watch('./js/*.js').on('change', browserSync.reload);
}
exports.style = style;
exports.watch = watch;

Gulp-sass won't compile scss files to css instead copy all files from scss folder to css folder

Hello i am pretty new to a gulp.
The problem is when i run default task with command "gulp" scss files dont compile instead copy to css folder
This is my gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'app'
}
})
})
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss')
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}));
})
gulp.task('watch', function() {
gulp.watch('app/scss/**/*.scss', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
})
gulp.task('default', function(callback) {
runSequence(['sass', 'browserSync', 'watch'],
callback
)
})
directory tree
app
|-scss
|- styles.scss
|- _layout.scss
|- _homepage.scss
|- _profile.scss
|- _contact.scss
|-css
in styles.scss i have :
$orange: #f29528;
$image: "../images/";
#import 'layout';
#import 'homepage';
#import 'profile';
#import 'contact';
You don't use sass() . Try :
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}));
})
Read more gulp-sass
I'm using this as my projects task handler with the files.scss and works just fine for me ATM.
I hope it works for you as well.
'use strict'
// #requesting packages
const gulp = require('gulp');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const cleancss = require('gulp-clean-css');
// #gulp task
gulp.task('sass', () =>
gulp.src('./scss/**/*.scss')
.pipe(sass({
outputStyle: 'nested',
sourceComments: false
}))
// *** The debug function isn't needed you can delete it if you want
.pipe(cleancss({debug: true}, function(details) {
console.log(details.name + ': ' + details.stats.originalSize);
console.log(details.name + ': ' + details.stats.minifiedSize);
}))
.pipe(autoprefixer({
versions: ['last 2 browsers']
}))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./css'))
);
// #gulp watch task
gulp.task('default', () => {
gulp.watch('./scss/*.scss', ['sass']);
});
Remember to change the path of the directories in the sass route.

Resources