Gulp livereload from build folder - javascript

Everything is working fine, except that LiveReload is not watching for changes, and therefore it does not auto-reload the page.
What am I doing wrong?
Here is my Gulp file:
// Gulp.js configuration
var
// modules
gulp = require('gulp'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
pug = require('gulp-pug'),
htmlclean = require('gulp-htmlclean'),
concat = require('gulp-concat'),
deporder = require('gulp-deporder'),
stripdebug = require('gulp-strip-debug'),
uglify = require('gulp-uglify'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
assets = require('postcss-assets'),
autoprefixer = require('autoprefixer'),
mqpacker = require('css-mqpacker'),
cssnano = require('cssnano'),
browserSync = require('browser-sync').create(),
// development mode?
devBuild = (process.env.NODE_ENV !== 'production'),
// folders
folder = {
src: 'src/',
build: 'build/'
};
// image processing
gulp.task('images', function () {
var out = folder.build + 'images/';
return gulp.src(folder.src + 'images/**/*')
.pipe(newer(out))
.pipe(imagemin({
optimizationLevel: 5
}))
.pipe(gulp.dest(out));
});
// Pug processing
gulp.task('pug', function buildHTML() {
var out = folder.build
return gulp.src(folder.src + 'views/*.pug')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest(out))
});
// HTML processing
gulp.task('html', ['images'], function () {
var
out = folder.build + 'html/',
page = gulp.src(folder.src + 'html/**/*')
.pipe(newer(out));
// minify production code
if (!devBuild) {
page = page.pipe(htmlclean());
}
return page.pipe(gulp.dest(out));
});
// JavaScript processing
gulp.task('js', function () {
var jsbuild = gulp.src(folder.src + 'js/**/*')
.pipe(deporder())
.pipe(concat('main.js'));
if (!devBuild) {
jsbuild = jsbuild
.pipe(stripdebug())
.pipe(uglify());
}
return jsbuild.pipe(gulp.dest(folder.build + 'js/'));
});
// CSS processing
gulp.task('css', ['images'], function () {
var postCssOpts = [
assets({
loadPaths: ['images/']
}),
autoprefixer({
browsers: ['last 2 versions', '> 2%']
}),
mqpacker
];
if (!devBuild) {
postCssOpts.push(cssnano);
}
return gulp.src(folder.src + 'scss/styles.scss')
.pipe(sass({
outputStyle: 'nested',
imagePath: 'images/',
precision: 3,
errLogToConsole: true
}))
.pipe(postcss(postCssOpts))
.pipe(gulp.dest(folder.build + 'css/'));
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: folder.build
},
port: 3000
});
});
// run all tasks
gulp.task('run', ['pug', 'html', 'css', 'js']);
// watch for changes
gulp.task('watch', ['browserSync'], function () {
// image changes
gulp.watch(folder.src + 'images/**/*', ['images']);
// pug changes
gulp.watch(folder.src + 'views/**/*', ['pug'], browserSync.reload);
// html changes
gulp.watch(folder.src + 'html/**/*', ['html'], browserSync.reload);
// javascript changes
gulp.watch(folder.src + 'js/**/*', ['js'], browserSync.reload);
// css changes
gulp.watch(folder.src + 'scss/**/*', ['css'], browserSync.reload);
});
// default task
gulp.task('default', ['run', 'watch']);

A sample of our working watch gulp configuration is like:
var watch = require('gulp-watch');
watch('./src/**/*.html', function () {
browserSync.reload();
});

Related

Upgrade Gulp 3 to Gulp 4 no reloading BrowserSync

I am trying to upgrade from gulp 3.9 to gulp 4, at first seems everything is working fine but when I make changes (sass, pug or html files) it not reload with browsersync), I do know now if watch or jekyll is the cause of this problem.
I am using:
Gulp: 4.0.0
Gulp CLI: 2.0.1
Npm: 6.4.0
Node: 10.9.0
what can be happening?
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var cp = require('child_process');
var pug = require('gulp-pug');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
var bourbon = require('bourbon').includePaths;
var rename = require('gulp-rename');
// Message
var messages = {
jekyllBuild: '<span style="color: white">Running:</span> $ jekyll build'
};
// Paths
var paths = {
html: {
src: ['*.html', '_layouts/*.html', '_posts/*', '_includes/*'],
dest: '_includes'
},
pugFiles: {
src: '_jadefiles/*.jade',
dest: '_includes'
},
styles: {
all: 'assets/css/**',
src: 'assets/css/main.scss',
dest: ['assets/css', '_site/assets/css']
},
scripts: {
src: ['assets/js/**/*.js', 'js/*.js'],
dest: ['js', '_site/assets/js']
}
}
// Compile Pug|Jade files into .html
gulp.task('pug', function() {
return gulp.src(paths.pugFiles.src)
.pipe(pug())
.pipe(gulp.dest(paths.pugFiles.dest));
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src(paths.styles.src)
.pipe(sass({
includePaths: [bourbon],
onError: browserSync.notify
}).on('error', sass.logError))
.pipe(gulp.dest(paths.styles.dest))
.pipe(prefix({
browsers: ['last 15 versions', '> 1%', 'ie 8', 'ie 7'],
cascade: true
}))
.pipe(rename({suffix: '.min', prefix : ''}))
.pipe(minifycss())
.pipe(browserSync.stream());
});
// Watch changes on files
gulp.task('watch', function() {
// gulp.watch(paths.scripts.src).on('change', browserSync.reload);
gulp.watch(paths.html.src, gulp.series('jekyll-rebuild'));
gulp.watch(paths.pugFiles.src, gulp.series('pug'));
gulp.watch(paths.styles.all, gulp.series('sass'));
gulp.watch(paths.html.dest).on('change', browserSync.reload);
});
// Build Jekyll
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
var pl = process.platform === "win32" ? "jekyll.bat" : "jekyll";
return cp.spawn(pl, ['build'], {stdio: 'inherit'})
.on('close', done);
});
// Rebuild Jekyll site
gulp.task('jekyll-rebuild',
gulp.series('jekyll-build', function () {
browserSync.reload();
})
);
// Static Server
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: '_site'
}
});
});
gulp.task('default', gulp.series('serve', gulp.parallel('sass', 'pug', 'watch', 'jekyll-build')));

Gulp - Exclude variable file name

I have my full gulp file below. It compiles my CSS, and then uses another function to take my CSS file, minify it, and then copy it over to another folder "assets/css".
The file I'm looking to exclude is mainStyle. If I don't exclude this, I get a perpetual loop in my watch task.
When I run the file, because I have the !mainStyle toward the bottom, I get the error "TypeError: pattern.indexOf is not a function".
var themename = 'themename';
var gulp = require('gulp'),
// Prepare and optimize code etc
autoprefixer = require('autoprefixer'),
browserSync = require('browser-sync').create(),
image = require('gulp-image'),
jshint = require('gulp-jshint'),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
cleanCSS = require('gulp-clean-css'),
// Only work with new or updated files
newer = require('gulp-newer'),
// Name of working theme folder
root = '../' + themename + '/',
scss = root + 'sass/',
js = root + 'js/',
img = root + 'images/',
languages = root + 'languages/';
mainStyle = root + 'style.css';
// CSS via Sass and Autoprefixer
gulp.task('css', function() {
return gulp.src(scss + '{style.scss,rtl.scss}')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'expanded',
indentType: 'tab',
indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
autoprefixer('last 2 versions', '> 1%')
]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
});
gulp.task('minify-css', () => {
return gulp.src(mainStyle)
.pipe(cleanCSS({level: {1: {specialComments: 0}}}, (details) => {
console.log(`${details.name}: ${details.stats.originalSize}`);
console.log(`${details.name}: ${details.stats.minifiedSize}`);
}))
.pipe(gulp.dest(root + '/assets/css/'));
});
// Optimize images through gulp-image
gulp.task('images', function() {
return gulp.src(img + 'RAW/**/*.{jpg,JPG,png}')
.pipe(newer(img))
.pipe(image())
.pipe(gulp.dest(img));
});
// JavaScript
gulp.task('javascript', function() {
return gulp.src([js + '*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest(js));
});
// Watch everything
gulp.task('watch', function() {
browserSync.init({
open: 'external',
proxy: 'example.local/',
port: 8080
});
gulp.watch([ root + '**/*.css', root + '**/*.scss', !mainStyle ], ['css']);
gulp.watch(js + '**/*.js', ['javascript']);
gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
gulp.watch(root + '**/*').on('change', browserSync.reload);
gulp.watch(root + 'style.css', ['minify-css'])
});
// Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
The way you have your rule written is actually returning false. Change it to a string so it's properly interpreted as a minimatch rule.
gulp.watch([ root + '**/*.css', root + '**/*.scss', `!${mainStyle}` ], ['css']);

Reload browsersync when js files change

There are two things with my gulpfile.js.
1: I want to reload browser when js files changed. Sass and html files are working correctly but, when js files change, no action in browser.
2: I just wonder about this topic: Which modules should I use for dynamic html files. Pug/jade or gulp-inject-partials.
Here is my gulpfile.js
var gulp = require('gulp'),
sass = require('gulp-sass'),
browserSync = require('browser-sync'),
reload = browserSync.reload(),
autoprefixer = require('gulp-autoprefixer'),
browserify = require('gulp-browserify'),
clean = require('gulp-clean'),
concat = require('gulp-concat'),
merge = require('merge-stream'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
injectPartials = require('gulp-inject-partials'),
pug = require('gulp-pug');
var sourcePath = {
sassSource: 'src/scss/*.scss',
htmlSource: 'src/*.html',
htmlPartialsSource: 'src/partial/*.html',
jsSource: 'src/js/**',
imgSource: 'src/img/**',
pugSource: 'src/views/*.pug'
}
var appPath = {
root: 'app/',
css: 'app/css',
js: 'app/js',
img: 'app/img'
}
gulp.task('clean-html', function() {
return gulp.src(appPath.root + '/*.html', {read: false, force: true})
.pipe(clean());
});
gulp.task('clean-script', function() {
return gulp.src(appPath.js + '/*.js', {read: false, force: true})
.pipe(clean());
});
gulp.task('script', ['clean-script'], function() {
return gulp.src(sourcePath.jsSource)
.pipe(concat('main.js'))
.pipe(browserify())
.pipe(gulp.dest(appPath.js))
});
gulp.task('html', function() {
return gulp.src(sourcePath.htmlSource)
.pipe(injectPartials())
.pipe(gulp.dest(appPath.root))
});
gulp.task('sass', function() {
var bootstrapCSS = gulp.src('./node_modules/bootstrap/dist/css/bootstrap.css'),
sassFiles;
sassFiles = gulp.src(sourcePath.sassSource)
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
return merge(bootstrapCSS, sassFiles)
.pipe(concat('app.css'))
.pipe(gulp.dest(appPath.css));
});
gulp.task('images', function() {
return gulp.src(sourcePath.imgSource)
.pipe(newer(appPath.img))
.pipe(imagemin())
.pipe(gulp.dest(appPath.img));
});
gulp.task('serve', function() {
browserSync.init([appPath.css + '/*.css', appPath.root + '/*.html', appPath.js + '/*.js'], {
server:{
baseDir: appPath.root
}
})
});
gulp.task('watch', ['serve', 'sass', 'clean-html', 'script', 'clean-script', 'images', 'html'], function() {
gulp.watch([sourcePath.sassSource], ['sass']);
gulp.watch([sourcePath.jsSource], ['script']);
gulp.watch([sourcePath.imgSource], ['images']);
gulp.watch([sourcePath.htmlSource, sourcePath.htmlPartialsSource], ['html']);
});
gulp.task('default', ['watch']);
I found a solution. I changed watch & server task.
gulp.task('watch', function () {
gulp.watch(sourcePath.sassSource, ['sass']);
gulp.watch(['src/view/**/*', sourcePath.pugSource], ['view']);
gulp.watch(sourcePath.jsSource, ['script']);
gulp.watch(sourcePath.imgSource, ['images']);
// init server
browserSync.init({
server: {
proxy: "local.build",
baseDir: appPath.root
}
});
gulp.watch([appPath.root + '**'], browserSync.reload);
});
gulp.task('default', ['watch']);
I was able to edit the gulp.task('serve') to accomplish this:
var reload = browserSync.reload;
gulp.task('serve', function () {
// Serve files from the root of this project
browserSync.init({
server: {
baseDir: "./"
}
});
gulp.watch("*.html").on("change", reload);
gulp.watch("./_assets/css/*.css").on("change", reload);
gulp.watch("./_assets/js/*.js").on("change", reload);
});

Getting gulp task to build two css files

I have a project using gulp to compile all my scss. Now I have a need for two separate builds. Currently my task builds out sites-bootstrap.css. I have another set of css files that is set up to build sites-life-bootstrap.css that will have minimal components in it. I just can't seem to get gulp to build that separate css file.
Below is my current working gulp file.js.
/* jshint node:true */
'use strict';
// generated on 2015-02-10 using generator-gulp-webapp 0.2.0
var gulp = require('gulp');
var fs = require('fs');
require('gulp-grunt')(gulp);
var runs = require('run-sequence');
var $ = require('gulp-load-plugins')();
//build the compile using assemble + grunt
//Note: Assemble's gulp task is very alpha - easier to do this
gulp.task('compile', function(){
gulp.run('grunt-compile');
});
gulp.task('styles', function () {
var sassPaths = ['./bower_components/bootstrap-sass-official/assets/stylesheets'];
return gulp.src('app/styles/sites-bootstrap.scss')
.pipe($.plumber())
.pipe($.sass({
style: 'expanded',
includePaths: sassPaths,
precision: 10
}))
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe($.replace('../bower_components/bootstrap-sass-official/assets/fonts/bootstrap','../fonts'))
.pipe(gulp.dest('dist/styles'));
});
gulp.task('jshint', function () {
return gulp.src('app/scripts/**/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('html', ['styles'], function () {
var lazypipe = require('lazypipe');
var cssChannel = lazypipe()
.pipe($.csso);
var assets = $.useref.assets({searchPath: '{.tmp,app}'});
//all the build instructions are in build.html NOT in the hbs files
return gulp.src('app/useref/build.html')
.pipe(assets)
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', cssChannel()))
.pipe(assets.restore()) //do the asset replacement in the html files
.pipe($.useref())
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', function () {
return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', function () {
return gulp.src([
'app/extras/*.*'
], {
dot: true
})
.pipe(gulp.dest('dist'));
});
/**
* clean out dist and .tmp
*/
gulp.task('clean', function (cb) {
var del = require('del');
del([
'./.tmp',
'./dist/*',
], cb);
});
gulp.task('connect', ['styles'], function () {
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
var app = require('connect')()
.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('dist'))
.use(serveIndex('dist'));
require('http').createServer(app)
.listen(9000)
.on('listening', function () {
console.log('Started connect web server on http://localhost:9000');
});
});
gulp.task('cdn', function(){
var json = fs.readFileSync('gulp-aws.json');
var aws = JSON.parse(json);
var opts = aws.cdn;
// create a new publisher
var publisher = $.awspublish.create(opts);
var sourceFolder = ['./dist/styles','./dist/fonts','./dist/images'];
return gulp.src(sourceFolder)
// gulp-awspublish-router defines caching and other options (see above)
//.pipe(awspublishRouter(awsPubRouterOpts))
// publisher will add Content-Length, Content-Type and headers specified above
// if not specified it will set x-amz-acl to public-read by default
// i think the parallelization was causing it to miss some files
.pipe(publisher.publish())
// .pipe(publisher.publish(null, { force: true }))
// delete stuff that has been deleted locally
// can't do this because it will kill 1.9
//.pipe(publisher.sync())
// create a cache file to speed up consecutive uploads
.pipe(publisher.cache())
// print upload updates to console
.pipe($.awspublish.reporter());
});
gulp.task('serve', function (done) {
runs( ['build'], ['watch'], ['open'], done);
});
gulp.task('open', function(){
require('opn')('http://localhost:9000');
});
gulp.task('watch', ['connect'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'dist/**/*.html',
'.tmp/styles/**/*.css',
'dist/scripts/**/*.js',
'dist/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/**/*.hbs', ['compile']);
});
gulp.task('reload', function(){
$.livereload.changed();
});
gulp.task('deploy', function(done) {
// return gulp.src('./dist/**/*')
// .pipe($.ghPages({origin: 'upstream'}));
console.error('DEPRECATED: Deployment to gh-pages is now handled by Travis CI.');
done();
});
gulp.task('build-report', function () {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('build', function (done) {
runs( ['clean'], ['jshint', 'html', 'images', 'fonts', 'extras'], 'compile', 'build-report', done);
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
Here was one attempt at just adding multiple outputs to the styles task:
gulp.task('styles', function () {
var sassPaths = ['./bower_components/bootstrap-sass-official/assets/stylesheets'];
return gulp.src('app/styles/sites-bootstrap.scss', 'app/styles/sites-lite-bootstrap.scss')
.pipe($.plumber())
.pipe($.sass({
style: 'expanded',
includePaths: sassPaths,
precision: 10
}))
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe($.replace('../bower_components/bootstrap-sass-official/assets/fonts/bootstrap','../fonts'))
.pipe(gulp.dest('dist/styles'));
});

Styles are not being updated in gulpfile.js using gulp-watch and gulp-server-livereload

If I make a change to my style sheet then the styles will be re-loaded but only once. I need the styles to reload after all changes.
I am new to using task managers so any help would be greatly appreciated.
gulpfile.js
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
sass = require('gulp-ruby-sass'),
server = require('gulp-server-livereload'),
bower_files = require('bower-files')(),
inject = require('gulp-inject'),
del = require('del'),
watch = require('gulp-watch'),
batch = require('gulp-batch'),
jasmine = require('gulp-jasmine'),
karma = require('karma').server,
src = 'app/',
dest = 'dist/',
cssDestFolder = src,
cssStyle = 'compressed',
serverSrc = dest;
/**
* Set distribution environment
*/
gulp.task('set-env-dist', function () {
cssDestFolder = dest;
cssStyle = 'compressed';
serverSrc = dest;
});
/**
* Set development environment
*/
gulp.task('set-env-dev', function () {
cssDestFolder = src;
cssStyle = 'expanded';
serverSrc = src;
});
/**
* Run test once and exit
*/
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
/**
* Concatenate and compress bower
*/
gulp.task('bower', function () {
gulp.src(bower_files.ext('js').files)
.pipe(concat('bower.min.js'))
.pipe(uglify())
.pipe(gulp.dest(dest));
});
/**
* Run server
*/
gulp.task('webServer', function () {
gulp.src(serverSrc)
.pipe(server({
livereload: true,
log: 'debug',
open: true
}));
});
/**
* Compress sass
*/
gulp.task('styles', function () {
console.log('in styles')
return sass(src + 'app.scss', {style: cssStyle})
.pipe(gulp.dest(cssDestFolder));
});
/**
* Concatenate and compress js
*/
gulp.task('scripts', function () {
return gulp.src([
src + 'app.js',
src + 'components/**/*.js',
src + '**/*.js',
'!' + src + 'bower_components/**/*.js',
'!' + src + 'components/**/*.spec.js',
'!' + src + '**/*.spec.js'
])
.pipe(concat('main.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest(dest));
});
gulp.task('watch', function () {
watch([
'app/**/*.scss',
'app/app.scss'
], batch(function () {
gulp.start('styles');
}));
});
gulp.task('build-dist', ['set-env-dist', 'scripts', 'styles', 'bower']);
gulp.task('serve-dist', ['set-env-dist', 'webServer', 'watch']);
gulp.task('serve', ['set-env-dev', 'sass', 'webServer']);
I've never used gulp-batch, but you are only running one gulp task in your watch. Try this,
gulp.task('watch', function () {
watch([
'app/**/*.scss',
'app/app.scss'
], ['styles']);
});

Categories

Resources