I'm trying to get Browser Sync and Live Reload working in my gulp file but it doesn't want to run correctly.
I want to be able to detect any file change in 'src' and my 'templates' folder which are both contained within the root. The gulp file is detecting the changes in the src folder fine but the template files are not getting reloaded in the browser on save.
Note:
I have the live reload chrome browser extension.
I'm not compiling the templates folder but am compiling everything in src to the web destination folder.
The Gulp File:
// -------------------- Configuration Settings --------------------
var config = {};
//basics
config.siteName = 'Franklin';
config.proxyDomain = 'https://franklin.test';
//source directory
config.src = 'src/';
//twig templates
config.templates = 'templates';
//destinations
config.dest = 'web/';
config.destJS = config.dest + 'assets/js';
config.destCSS = config.dest + 'assets/css';
config.destFonts = config.dest + 'assets/fonts';
config.destPWA = config.dest;
//globs
config.globs = {
templates : config.templates + '/**/*.twig',
scss : config.src + 'scss/**/*.scss',
js : {
individual : config.src + 'js/individual/**/*.js',
combined : [
config.src + 'js/combined/libs/*.js',
config.src + 'js/combined/plugins/*.js',
config.src + 'js/combined/pluginSubs/*.js',
config.src + 'js/combined/site/*.js',
config.src + 'js/combined/site.js'
]
},
fonts : config.src + 'fonts/**/*',
pwa : config.src + 'pwa/**/*',
watched : [
config.templates + '/**/*.twig',
config.destJS + '/**/*.min.js',
config.destCSS + '/**/*.min.css',
config.destFonts + '/**/*',
config.destPWA + '/**/*'
]
};
//browser sync
config.browserSync = {
files: config.globs.watched,
proxy: config.proxyDomain
};
// -------------------- Require Statements --------------------
var gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
livereload = require('gulp-livereload'),
browserSync = require('browser-sync').create(),
newer = require('gulp-newer'),
notify = require('gulp-notify'),
plumber = require('gulp-plumber'),
rename = require('gulp-rename'),
sass = require('gulp-sass'),
size = require('gulp-size'),
uglify = require('gulp-uglify'),
watch = require('gulp-watch'),
path = require('path'),
cssnano = require('gulp-cssnano'),
sourcemaps = require('gulp-sourcemaps'),
lazypipe = require('lazypipe'),
fs = require('fs');
// -------------------- Notification Icon Detection --------------------
/**
* Checks to see if a file exists.
*
* #param filePath
* #returns {*}
*/
function fileExists(filePath)
{
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
}
var iconPath = path.join(__dirname, 'gulp.png');
var icon = fileExists( iconPath ) ? iconPath : null;
// -------------------- Plumber Error Handler --------------------
var plumberErrorHandler = function(err) {
console.log( 'plumber error! "' + err.message + '"' );
notify.onError({
title: config.siteName,
message: "Error: <%= err.message %>",
sound: 'Pop'
});
this.emit('end');
};
// -------------------- Processors --------------------
//individual scripts (not combined)
var jsIndividualScripts = lazypipe()
.pipe(plumber, {errorHandler: plumberErrorHandler})
.pipe(newer, { dest: config.destJS, ext: '.min.js' })
.pipe(gulp.dest, config.destJS)
.pipe(size, {showFiles: true})
.pipe(uglify)
.pipe(rename, { suffix: '.min' })
.pipe(gulp.dest, config.destJS)
.pipe(size, {showFiles: true});
//combined scripts
var jsCombinedScripts = lazypipe()
.pipe(plumber, {errorHandler: plumberErrorHandler})
.pipe(newer, config.dest + 'js/scripts.min.js')
.pipe(concat, 'scripts.js')
.pipe(gulp.dest, config.destJS)
.pipe(size, {showFiles: true})
.pipe(uglify)
.pipe(rename, { suffix: '.min' })
.pipe(gulp.dest, config.destJS)
.pipe(size, {showFiles: true});
//scss compiling
var scssProcessing = lazypipe()
.pipe(plumber, {errorHandler: plumberErrorHandler})
.pipe(sass, {outputStyle: ':compact'})
.pipe(autoprefixer, 'last 2 version')
.pipe(gulp.dest, config.destCSS)
.pipe(size, {showFiles: true})
.pipe(rename, { suffix: '.min' })
.pipe(sourcemaps.init)
.pipe(cssnano)
.pipe(sourcemaps.write, '.')
.pipe(gulp.dest, config.destCSS)
.pipe(size, {showFiles: true});
//fonts compiling
var fontsProcessing = lazypipe()
.pipe(plumber, {errorHandler: plumberErrorHandler})
.pipe(gulp.dest, config.destFonts);
//pwa compiling
var pwaProcessing = lazypipe()
.pipe(plumber, { errorHandler: plumberErrorHandler })
.pipe(gulp.dest, config.destPWA);
// -------------------- Tasks --------------------
//styles task
gulp.task('styles', function() {
if ( browserSync.active ) {
return gulp.src(config.globs.scss)
.pipe(scssProcessing())
.pipe(browserSync.reload({stream:true}));
}
return gulp.src(config.globs.scss).pipe(scssProcessing());
});
//template task
gulp.task('templates', function() {
if ( browserSync.active ) {
return gulp.src(config.globs.templates)
.pipe(browserSync.reload({stream:true}));
}
});
//scripts individual task
gulp.task('scripts-individual', function() {
return gulp.src(config.globs.js.individual).pipe(jsIndividualScripts());
});
//scripts combined task
gulp.task('scripts-combined', function() {
return gulp.src(config.globs.js.combined).pipe(jsCombinedScripts());
});
//fonts task
gulp.task('fonts', function() {
return gulp.src(config.globs.fonts).pipe(fontsProcessing());
});
//pwa task
gulp.task('pwa', function () {
return gulp.src(config.globs.pwa).pipe(pwaProcessing());
});
//watch task
gulp.task('live', function() {
//watch all .scss files
gulp.watch(config.globs.scss, ['styles']);
//watch all twig template files
gulp.watch(config.globs.templates, ['templates']);
//watch each individual .js file
watch(config.globs.js.individual).pipe(jsIndividualScripts());
//watch all combined .js files
gulp.watch(config.globs.js.combined, ['scripts-combined']);
});
//default task - one time styles and scripts
gulp.task('default', ['styles', 'templates', 'scripts-individual', 'scripts-combined', 'fonts', 'pwa']);
//start browser-sync server
gulp.task('serve-bs', ['live'], function() {
browserSync.init(config.browserSync)
});
//start livereload
gulp.task('watch', ['live'], function() {
livereload.listen();
//watch for changes on transpired templates, css, and js files
gulp.watch(config.globs.watched, function(event) {
gulp.src(event.path)
.pipe(plumber({errorHandler: plumberErrorHandler}))
.pipe(livereload())
.pipe(notify({
title: config.siteName,
message: event.type + ': ' + event.path.replace(__dirname, '').replace(/\\/g, '/') + ' was reloaded',
sound: 'Pop',
icon: icon
})
);
});
});
Related
I am not able to get the sass code I write to compile into CSS when I use any of the following commands:
gulp watch
gulp scss-for-prod
gulp scripts-for-prod
The strange thing is though that fork picks up when I make a change
SOLVED: add a clean package.json file
This is the Gulp.js
// Defining requirements
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var cssnano = require('gulp-cssnano');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var terser = require('gulp-terser');
//var uglify = require('gulp-uglify');
var merge2 = require('merge2');
var imagemin = require('gulp-imagemin');
var ignore = require('gulp-ignore');
var rimraf = require('gulp-rimraf');
var clone = require('gulp-clone');
var merge = require('gulp-merge');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync').create();
var del = require('del');
var cleanCSS = require('gulp-clean-css');
var gulpSequence = require('gulp-sequence');
var replace = require('gulp-replace');
var autoprefixer = require('gulp-autoprefixer');
//var babel = require('gulp-babel');
var webpack = require('webpack-stream');
//var haml = require('gulp-haml');
// Configuration file to keep your code DRY
var cfg = require('./gulpconfig.json');
var paths = cfg.paths;
// Run:
// gulp sass + cssnano + rename
// Prepare the min.css for production (with 2 pipes to be sure that "theme.css" == "theme.min.css")
gulp.task('scss-for-prod', function () {
var source = gulp.src(paths.sass + '/*.scss')
.pipe(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sass());
var pipeoutput = source.pipe(clone())
//.pipe(minifycss())
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest(paths.css));
return pipeoutput;
});
// Run:
// gulp sourcemaps + sass + reload(browserSync)
// Prepare the child-theme.css for the development environment
gulp.task('scss-for-dev', function () {
gulp.src(paths.sass + '/*.scss')
.pipe(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sass())
.pipe(sourcemaps.write(undefined, { sourceRoot: null }))
.pipe(gulp.dest(paths.css));
});
gulp.task('watch-scss', ['browser-sync'], function () {
gulp.watch(paths.sass + '/**/*.scss', ['scss-for-dev']);
});
// Run:
// gulp sass
// Compiles SCSS files in CSS
gulp.task('sass', function () {
var stream = gulp.src(paths.sass + '/*.scss')
.pipe(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sass({ errLogToConsole: true }))
.pipe(autoprefixer('last 2 versions'))
.pipe(gulp.dest(paths.css));
return stream;
});
// Run:
// gulp watch
// Starts watcher. Watcher runs gulp sass task on changes
gulp.task('watch', function () {
gulp.watch(paths.haml + '/**/*.haml', ['convert-haml']);
gulp.watch(paths.sass + '/**/*.scss', ['styles']);
gulp.watch([paths.dev + '/js/**/*.js', 'js/**/*.js', '!js/theme.js', '!js/theme.min.js'], ['scripts']);
//Inside the watch task.
gulp.watch(paths.imgsrc + '/**', ['imagemin-watch']);
//browserSync.reload();
});
/**
* Ensures the 'imagemin' task is complete before reloading browsers
* #verbose
*/
gulp.task('imagemin-watch', ['imagemin'], function (done) {
browserSync.reload();
done();
});
// Run:
// gulp imagemin
// Running image optimizing task
gulp.task('imagemin', function () {
gulp.src(paths.imgsrc + '/**')
.pipe(imagemin())
.pipe(gulp.dest(paths.img));
});
// Run:
// gulp cssnano
// Minifies CSS files
gulp.task('cssnano', function () {
return gulp.src(paths.css + '/theme.css')
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(rename({ suffix: '.min' }))
.pipe(cssnano({ discardComments: { removeAll: true } }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(paths.css));
});
gulp.task('minifycss', function () {
return gulp.src(paths.css + '/theme.css')
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(cleanCSS({ compatibility: '*' }))
.pipe(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(rename({ suffix: '.min' }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(paths.css));
});
gulp.task('cleancss', function () {
return gulp.src(paths.css + '/*.min.css', { read: false }) // Much faster
.pipe(ignore('theme.css'))
.pipe(rimraf());
});
//gulp.task( 'convert-haml', function( callback ) {
// gulp.src('./haml/**/*.haml')
// .pipe(haml({ext: '.php'}))
// .pipe(gulp.dest('./'));
//} );
gulp.task('styles', function (callback) {
//gulpSequence('sass', 'minifycss')(callback);
gulpSequence('sass', 'cleancss')(callback);
});
// Run:
// gulp browser-sync
// Starts browser-sync task for starting the server.
gulp.task('browser-sync', function () {
browserSync.init(cfg.browserSyncWatchFiles, cfg.browserSyncOptions);
});
// Run:
// gulp watch-bs
// Starts watcher with browser-sync. Browser-sync reloads page automatically on your browser
gulp.task('watch-bs', ['browser-sync', 'watch', 'scripts'], function () {
});
// gulp scripts.
// Uglifies and concat all JS files into one
gulp.task('scripts', function () {
var scripts = [
//paths.dev + '/js/paginate.js',
//paths.dev + "/js/Select2.js",
paths.dev + "/js/slick/slick.js",
paths.dev + '/js/main.js',
];
gulp.src(scripts)
//.pipe(babel())
.pipe(webpack({
mode: 'development'
}))
.pipe(concat('theme.js'))
.pipe(gulp.dest(paths.js));
});
gulp.task('scripts-for-prod', function () {
var scripts = [
//paths.dev + '/js/paginate.js',
//paths.dev + "/js/Select2.js",
paths.dev + "/js/slick/slick.js",
paths.dev + '/js/main.js',
];
gulp.src(scripts)
//.pipe(babel())
.pipe(webpack({
mode: 'development'
}))
.pipe(concat('theme.min.js'))
//.pipe( uglify().on('error', function(e){
// console.log(e);
// }) )
/*.pipe(terser().on('error', function(e){
console.log(e);
}) )*/
.pipe(gulp.dest(paths.js));
});
// Deleting any file inside the /src folder
gulp.task('clean-source', function () {
return del(['src/**/*']);
});
// Run:
// gulp copy-assets.
// Copy all needed dependency assets files from bower_component assets to themes /js, /scss and /fonts folder. Run this task after bower install or bower update
////////////////// All Bootstrap SASS Assets /////////////////////////
gulp.task('copy-assets', function () {
// Tachyons CSS
//var stream = gulp.src( paths.node + 'tachyons-sass/tachyons.scss' )
//.pipe( gulp.dest( paths.dev + '/sass/tachyons-sass' ) );
var stream = gulp.src(paths.node + 'normalize-scss/sass/**/*')
.pipe(gulp.dest(paths.dev + '/sass/normalize-scss'));
//gulp.src( paths.node + 'tachyons-sass/scss/*.scss' )
//.pipe( gulp.dest( paths.dev + '/sass/tachyons-sass/scss' ) );
// Flexbox Grid
//gulp.src( paths.node + 'flexboxgrid-sass/flexboxgrid.scss' )
//.pipe( gulp.dest( paths.dev + '/sass/flexboxgrid-sass' ) );
//gulp.src( paths.node + 'sass-flex-mixin/**/*' )
//.pipe( gulp.dest( paths.dev + '/sass/sass-flex-mixin' ) );
gulp.src(paths.node + '#drewbot/sass-flexbox-grid/public/sass-flexbox/scss/**/*')
.pipe(gulp.dest(paths.dev + '/sass/sass-flexbox-grid'));
////////////////// All Bootstrap 4 Assets /////////////////////////
// Copy all JS files
//var stream = gulp.src( paths.node + 'bootstrap/dist/js/**/*.js' )
// .pipe( gulp.dest( paths.dev + '/js/bootstrap4' ) );
// Copy all Bootstrap SCSS files
//gulp.src( paths.node + 'bootstrap/scss/**/*.scss' )
// .pipe( gulp.dest( paths.dev + '/sass/bootstrap4' ) );
////////////////// End Bootstrap 4 Assets /////////////////////////
gulp
.src(paths.node + "slick-carousel-latest/slick/slick.js")
.pipe(gulp.dest(paths.dev + "/js/utils/slick"));
gulp
.src(paths.node + "slick-carousel-latest/slick/*")
.pipe(gulp.dest(paths.dev + "/sass/slick"));
gulp
.src(paths.node + "slick-carousel-latest/slick/fonts/*")
.pipe(gulp.dest(paths.css + "/fonts"));
//gulp.src(paths.node + 'vanillajs-datepicker/dist/**/*')
// .pipe(gulp.dest(paths.dev + '/js/utils/vanillajs-datepicker'));
gulp.src(paths.node + 'js-datepicker/src/**/*')
.pipe(gulp.dest(paths.dev + '/js/utils/js-datepicker'));
gulp.src(paths.node + 'js-datepicker/dist/**/*')
.pipe(gulp.dest(paths.dev + '/js/utils/js-datepicker'));
// Copy Sass Mq
gulp.src(paths.node + 'sass-mq/_mq.scss')
.pipe(gulp.dest(paths.dev + '/sass/sass-mq'));
// Copy all Font Awesome Fonts
gulp.src(paths.node + '#fortawesome/fontawesome-free/**/*.{ttf,woff,woff2,eot,svg}')
.pipe(gulp.dest('./fonts/fortawesome'));
// Copy all Font Awesome SCSS files
gulp.src(paths.node + '#fortawesome/fontawesome-free/scss/**/*.scss')
.pipe(gulp.dest(paths.dev + '/sass/fortawesome'));
return stream;
});
// Deleting the files distributed by the copy-assets task
gulp.task('clean-vendor-assets', function () {
return del([
paths.dev + '/js/vanillajs-datepicker/**',
paths.dev + '/sass/sass-flex-mixin/**',
paths.dev + '/sass/flexboxgrid-sass/**',
'./fonts/*wesome*.{ttf,woff,woff2,eot,svg}',
paths.dev + '/sass/fortawesome/**',
paths.dev + "/js/utils/slick/**",
paths.dev + "/sass/slick/**",
paths.fonts + "/slick/**",
paths.vendor !== '' ? (paths.js + paths.vendor + '/**') : ''
]);
});
// Run
// gulp dist
// Copies the files to the /dist folder for distribution as simple theme
gulp.task('dist', ['clean-dist'], function () {
return gulp.src(['**/*', '!' + paths.bower, '!' + paths.bower + '/**', '!' + paths.node, '!' + paths.node + '/**', '!' + paths.dev, '!' + paths.dev + '/**', '!' + paths.dist, '!' + paths.dist + '/**', '!' + paths.distprod, '!' + paths.distprod + '/**', '!' + paths.sass, '!' + paths.sass + '/**', '!readme.txt', '!readme.md', '!package.json', '!package-lock.json', '!gulpfile.js', '!gulpconfig.json', '!CHANGELOG.md', '!.travis.yml', '!jshintignore', '!codesniffer.ruleset.xml', '*'], { 'buffer': false })
//.pipe( replace( '/js/jquery.slim.min.js', '/js' + paths.vendor + '/jquery.slim.min.js', { 'skipBinary': true } ) )
.pipe(replace('/js/main.js', '/js' + paths.vendor + '/main.js', { 'skipBinary': true }))
.pipe(gulp.dest(paths.dist));
});
// Deleting any file inside the /dist folder
gulp.task('clean-dist', function () {
return del([paths.dist + '/**']);
});
// Run
// gulp dist-product
// Copies the files to the /dist-prod folder for distribution as theme with all assets
gulp.task('dist-product', ['clean-dist-product'], function () {
return gulp.src(['**/*', '!' + paths.bower, '!' + paths.bower + '/**', '!' + paths.node, '!' + paths.node + '/**', '!' + paths.dist, '!' + paths.dist + '/**', '!' + paths.distprod, '!' + paths.distprod + '/**', '*'])
.pipe(gulp.dest(paths.distprod));
});
// Deleting any file inside the /dist-product folder
gulp.task('clean-dist-product', function () {
return del([paths.distprod + '/**']);
});
I just started to use Gulp with BrowserSync.
Please, help me with following issue: When I save my SCSS files BrowserSync not refreshes the webpage but saves files OK. Here is what happening in the console:
[21:37:48] Starting 'css'...
[Browsersync] 1 file changed (main.min.css)
[21:37:48] Finished 'css' after 206 ms
So no message
"[Browsersync] Reloading Browsers..."
This problem only with SCSS files, JS and HTML work correctly. Here is my gulpfile.js:
let project_folder = require("path").basename(__dirname);
let source_folder = "#src";
let fs = require('fs');
let path = {
build: {
html: project_folder + "/",
css: project_folder + "/css/",
js: project_folder + "/js/",
img: project_folder + "/images/",
fonts: project_folder + "/fonts/",
},
src: {
html: [source_folder + "/*.html", "!" + source_folder + "/_*.html"],
css: source_folder + "/styles/main.scss",
js: source_folder + "/js/main.js",
img: source_folder + "/images/**/*.{jpg,png,svg,gif,ico,webp}",
fonts: source_folder + "/fonts/*.{ttf,otf,woff,woff2}",
},
watch: {
html: source_folder + "/**/*.html",
css: source_folder + "/styles/**/*.scss",
js: source_folder + "/js/**/*.js",
img: source_folder + "/images/**/*.{jpg,png,svg,gif,ico,webp}"
},
clean: "./" + project_folder + "/"
}
let { src, dest } = require('gulp'),
gulp = require('gulp'),
browsersync = require("browser-sync").create(),
include = require('gulp-include'),
del = require("del"),
scss = require("gulp-sass"),
autoprefixer = require("gulp-autoprefixer"),
group_media = require("gulp-group-css-media-queries"),
clean_css = require("gulp-clean-css"),
rename = require("gulp-rename"),
uglify = require("gulp-uglify-es").default,
imagemin = require("gulp-imagemin"),
webp = require('gulp-webp'),
webphtml = require('gulp-webp-html'),
webpcss = require("gulp-webpcss"),
svgSprite = require('gulp-svg-sprite');
function browserSync(params) {
browsersync.init({
server: {
baseDir: "./" + project_folder + "/"
},
port: 3000,
notify: false
})
}
function html() {
return src(path.src.html)
.pipe(include())
.pipe(webphtml())
.pipe(dest(path.build.html))
.pipe(browsersync.stream())
}
function css() {
return src(path.src.css)
.pipe(
scss({
outputStyle: "expanded"
})
)
.pipe(
group_media()
)
.pipe(
autoprefixer({
overrideBrowserslist: ["last 5 versions"],
cascade: true
})
)
.pipe(webpcss())
.pipe(dest(path.build.css))
.pipe(clean_css())
.pipe(
rename({
extname: ".min.css"
})
)
.pipe(dest(path.build.css))
.pipe(browsersync.stream())
}
function js() {
return src(path.src.js)
// .pipe(fileinclude())
.pipe(include())
.pipe(dest(path.build.js))
.pipe(
uglify()
)
.pipe(
rename({
extname: ".min.js"
})
)
.pipe(dest(path.build.js))
.pipe(browsersync.stream())
}
function images() {
return src(path.src.img)
.pipe(
webp({
quality: 70
})
)
.pipe(dest(path.build.img))
.pipe(src(path.src.img))
.pipe(
imagemin({
progressive: true,
svgoPlugins: [{ removeViewBox: false }],
interlaced: true,
optimizationLevel: 3 // 0 to 7
})
)
.pipe(dest(path.build.img))
.pipe(browsersync.stream())
}
function fonts() {
return src(path.src.fonts)
.pipe(dest(path.build.fonts));
};
gulp.task('svgSprite', function () {
return gulp.src([source_folder + '/iconsprite/*.svg'])
.pipe(svgSprite({
mode: {
stack: {
sprite: "../icons/icons.svg", //sprite file name
example: true
}
},
}
))
.pipe(dest(path.build.img))
})
function watchFiles(params) {
gulp.watch([path.watch.html], html);
gulp.watch([path.watch.css], css);
gulp.watch([path.watch.js], js);
gulp.watch([path.watch.img], images);
}
function clean(params) {
return del(path.clean);
}
let build = gulp.series(clean, gulp.parallel(js, css, html, images, fonts));
let watch = gulp.parallel(build, watchFiles, browserSync);
exports.fonts = fonts;
exports.images = images;
exports.js = js;
exports.css = css;
exports.html = html;
exports.build = build;
exports.watch = watch;
exports.default = watch;
I'm very new to gulp and seeing as how complex the Roots's Sage gulpfile is, I'm so lost as to which block of code I should put in my code in.
The usage examples for both packages is as follows:
CSS Shrink
var gulp = require('gulp');
var cssshrink = require('gulp-cssshrink');
gulp.task('default', function() {
gulp.src('css/**/*.css')
.pipe(cssshrink())
.pipe(gulp.dest('dist/css/'));
});
Combine Media Queries
var cmq = require('gulp-combine-media-queries');
gulp.task('cmq', function () {
gulp.src('src/**/*.css')
.pipe(cmq({
log: true
}))
.pipe(gulp.dest('dist'));
});
Manifest.json file:
{
"dependencies": {
"main.js": {
"files": [
"scripts/main.js"
],
"main": true
},
"main.css": {
"files": [
"styles/main.scss"
],
"main": true
},
"customizer.js": {
"files": [
"scripts/customizer.js"
]
},
"jquery.js": {
"bower": [
"jquery"
]
}
},
"config": {
"devUrl": "http://yaharga/"
}
}
I tried to put it in the Styles task at the gulpfile.js, but nothing happened:
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var cmq = require('gulp-combine-media-queries');
var cssshrink = require('gulp-cssshrink');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
/************************* This is where I added it! *************************/
gulp.src(path.dist + 'styles/main.css')
.pipe(cssshrink())
.pipe(cmq())
.pipe(gulp.dest(path.dist + 'styles/main.css'));
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
Ideally, I would need to capture the main.css code and implement the cmq and cssshrink to it just before it is finally exported into the distribution folder.
I followed the post on Roots Discourse to help me do it; will update with full answer once done.
I am trying to merge two gulp sources as follows:
gulp.task("build", ["clean"], function () {
var sb = gulp.src([
paths.bower + "jquery/jquery.js",
paths.bower + "angular/angular.js"
])
.pipe(flatten())
.pipe(gulp.dest(paths.scripts.vnd));
var sm = gulp.src([
paths.scripts.vnd + "jquery.js",
paths.scripts.vnd + "angular.js"
])
.pipe(concat("app.js"))
.pipe(gulp.dest(paths.scripts.dst))
.pipe(rename("app.min.js"))
.pipe(uglify())
.pipe(gulp.dest(paths.scripts.dst));
return merge(sb, sm);
});
Somehow only the first one is executed.
However, if I move the second one to another task with dependency on build then both are executed ...
Am I doing the merging the wrong way?
UPDATE 1
I updated my task to build both LESS files and JS files so I have:
var
gulp = require("gulp"),
fs = require("fs"),
merge = require("merge2"),
concat = require("gulp-concat"),
flatten = require("gulp-flatten"),
less = require('gulp-less'),
minify = require('gulp-minify-css'),
rename = require("gulp-rename"),
rimraf = require("gulp-rimraf"),
uglify = require("gulp-uglify");
var paths = {
bower: "./bower_components/",
scripts: {
app: "./" + "/scripts/app/",
dst: "./" + "/scripts/dst/",
vnd: "./" + "/scripts/vnd/"
},
styles: {
app: "./" + project.webroot + "/styles/app/",
dst: "./" + project.webroot + "/styles/dst/"
}
};
gulp.task("build", function () {
var sbm = gulp.src([
paths.styles.app + "*.less",
paths.styles.vnd + "*.less"
])
.pipe(less())
.pipe(minify())
.pipe(concat("app.css"))
.pipe(gulp.dest(paths.styles.dst))
.pipe(rename("app.min.css"))
.pipe(gulp.dest(paths.styles.dst));
var scb = gulp.src(
[
paths.bower + "jquery/jquery.js",
paths.bower + "angular/angular.js"
])
.pipe(flatten())
.pipe(gulp.dest(paths.scripts.vnd));
var scm = gulp.src(
[
paths.scripts.vnd + "jquery.js",
paths.scripts.vnd + "angular.js"
])
.pipe(concat("app.js"))
.pipe(gulp.dest(paths.scripts.dst))
return merge(sbm, scb, scm);
});
Somehow, this only executes sbm ... Does anyone knows why?
I also tried #topleft's suggestion but when including the LESS tasks at the end the app.min.js file get's the Less code in it ...
try this with merge2 plugin, that's how I do it
var merge = require('merge2');
gulp.task("build", ["clean"], function () {
var sb = gulp.src([
paths.bower + "jquery/jquery.js",
paths.bower + "angular/angular.js"
])
.pipe(flatten())
.pipe(gulp.dest(paths.scripts.vnd));
var sm = gulp.src([
paths.scripts.vnd + "jquery.js",
paths.scripts.vnd + "angular.js"
])
return merge(sb, sm)
.pipe(concat("app.js"))
.pipe(gulp.dest(paths.scripts.dst))
.pipe(rename("app.min.js"))
.pipe(uglify())
.pipe(gulp.dest(paths.scripts.dst));
});
as an example, here is how I merge my two LESS streams : (one is unCSS'ed, the other is not)
/* ===== LESS START ===== */
gulp.task('less', function() {
// Get static styles
var streamMain = gulp.src([
srcAssets + '/less/**/*.less',
srcAssets + '!/less/**/interactive.less',])
// Convert to CSS
.pipe(less())
// Remove unused CSS rules
.pipe(uncss({
html: [dest + '/index.html']
}))
// Get dynamic styles
var streamEvents = gulp.src(srcAssets + '/less/global/interactive.less')
// Convert to CSS
.pipe(less())
// Merge dynamic and static styles
return merge(streamMain, streamEvents)
// Concatenate in a single file
.pipe(concat('main.css'))
// Remove all comments
.pipe(stripCssComments({
all: true
}))
// Autoprefixer for browser compatibility
.pipe(autoprefixer())
// Compression
.pipe(minifyCSS())
// Output file
.pipe(gulp.dest(dest + '/css'));
});
/* ===== LESS END ===== */
I'm trying to use gulp-data with gulp-jade in my workflow but I'm getting an error related to the gulp-data plugin.
Here is my gulpfile.js
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserSync = require('browser-sync'),
jade = require('gulp-jade'),
data = require('gulp-data'),
path = require('path'),
sass = require('gulp-ruby-sass'),
prefix = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
process = require('child_process');
gulp.task('default', ['browser-sync', 'watch']);
// Watch task
gulp.task('watch', function() {
gulp.watch('*.jade', ['jade']);
gulp.watch('public/css/**/*.scss', ['sass']);
gulp.watch('public/js/*.js', ['js']);
});
var getJsonData = function(file, cb) {
var jsonPath = './data/' + path.basename(file.path) + '.json';
cb(require(jsonPath))
};
// Jade task
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(plumber())
.pipe(data(getJsonData))
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('Build/'))
.pipe(browserSync.reload({stream:true}));
});
...
// Browser-sync task
gulp.task('browser-sync', ['jade', 'sass', 'js'], function() {
return browserSync.init(null, {
server: {
baseDir: 'Build'
}
});
});
And this is a basic json file, named index.jade.json
{
"title": "This is my website"
}
The error I get is:
Error in plugin 'gulp-data'
[object Object]
You are getting error because in getJsonData you pass required data as first argument to the callback. That is reserved for possible errors.
In your case the callback isn't needed. Looking at gulp-data usage example this should work:
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
Full example:
var gulp = require('gulp');
var jade = require('gulp-jade');
var data = require('gulp-data');
var path = require('path');
var fs = require('fs');
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('build/'));
});
Use this if you're running the task on gulp.watch:
.pipe(data(function(file) {
return JSON.parse(fs.readFileSync('./data/' + path.basename(file.path) + '.json'));
}))