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();
});
I'm currently working on a gulp project and I have this gulpfile.js
var config = require('./config.json'),
gulp = require('gulp'),
watch = require('gulp-watch'),
connect = require('gulp-connect'),
runSequence = require('run-sequence');
gulp.task('server', function() {
connect.server({
root: './',
port: config.port,
livereload: true
});
});
gulp.task('html', function() {
gulp.src('./' + config.creatives + '/**/*.html')
.pipe(connect.reload());
});
gulp.task('watch', function() {
gulp.watch(['./' + config.creatives + '/**/*.html'], ['html']);
gulp.watch(['./' + config.creatives + '/**/*.css'], ['html']);
});
gulp.task('default', function() {
return runSequence('server', ['html', 'watch']);
});
the config.json content is
{
"port" : "2727",
"creatives" : "creatives"
}
My question is how can I add a temporary script file to the page I'm currently viewing? I saw connect-livereload is adding livereload.js on the bottom of my page & I would like to do the same. Thanks in advance.
--- UPDATE--- 14-03-2017 ---
I update the gulpfile.js server with the code below, but the test.js is being injected to the file permanently.
gulp.task('server', function() {
connect.server({
...
livereload: true,
middleware: function(connect, option) {
return [
function(req, res, next) {
var file, path;
if (req.url.indexOf('preview') > -1) {
file = req.url;
path = file.replace('index.html', '')
gulp.src('./' + file)
.pipe(insertLines({
'before': /<\/body>$/,
'lineBefore': '<script type="text/javascript" src="test.js"></script>'
}))
.pipe(gulp.dest('./' + path));
}
next();
}
]
}
});
});
I only need to add the test.js when the server starts & remove if when server ends.
I made a solution by editing the module itself using gulp.
Not sure if this is correct, but for me, this is fine (for now).
Solution
I made a update-module.js file and has this scripts:
var gulp = require('gulp'),
tap = require('gulp-tap'),
rename = require('gulp-rename');
gulp.task('default', function() {
return gulp.src('./node_modules/connect-livereload/index.js')
.pipe(rename('~index.js'))
.pipe(gulp.dest('./node_modules/connect-livereload/'))
.pipe(tap(function(file, callback) {
var newFile = file.contents.toString(),
oldText = 'return \'<script src="\' + src + \'" async="" defer=""></script>\'',
newtext = 'return \'<script src="\' + src + \'" async="" defer=""></script><script src="http://localhost:3000/temp.js" ></script>\'';
newContents = newFile.replace(oldText, newtext);
file.contents = new Buffer(newContents);
return file;
}))
.pipe(rename('index.js'))
.pipe(gulp.dest('./node_modules/connect-livereload/'));
});
I run this script once by typing gulp --gulpfile ./update-module.js on my terminal.
What it does is look for connect-livereload module and copy the index.js, rename it to ~index.js (for backup), then modify index.js to include my temporary script (temp.js) and save it on same location as index.js.
Gulp browser-sync is not reloading my browser. When I hit save on my project it builds everything fine. My browser blinks and says "Connected to Browser-sync" on the upper right hand corner. It does not load the changes though. When I manually hit refresh, on chrome, it will load the changes. I've been up and down the gulp file and can find nothing wrong. Any advice?
Gulp.js file:
var $ = require('gulp-load-plugins')();
var argv = require('yargs').argv;
var browser = require('browser-sync');
var gulp = require('gulp');
var panini = require('panini');
var rimraf = require('rimraf');
var sequence = require('run-sequence');
var sherpa = require('style-sherpa');
// Check for --production flag
var isProduction = !!(argv.production);
// Port to use for the development server.
var PORT = 8000;
// Browsers to target when prefixing CSS.
var COMPATIBILITY = ['last 2 versions', 'ie >= 9'];
// File paths to various assets are defined here.
var PATHS = {
assets: [
'src/assets/**/*',
'!src/assets/{img,js,scss}/**/*'
],
sass: [
'bower_components/foundation-sites/scss',
'bower_components/motion-ui/src/'
],
javascript: [
'bower_components/jquery/dist/jquery.js',
'bower_components/what-input/what-input.js',
'bower_components/foundation-sites/js/foundation.core.js',
'bower_components/foundation-sites/js/foundation.util.*.js',
// Paths to individual JS components defined below
'bower_components/foundation-sites/js/foundation.abide.js',
'bower_components/foundation-sites/js/foundation.accordion.js',
'bower_components/foundation-sites/js/foundation.accordionMenu.js',
'bower_components/foundation-sites/js/foundation.drilldown.js',
'bower_components/foundation-sites/js/foundation.dropdown.js',
'bower_components/foundation-sites/js/foundation.dropdownMenu.js',
'bower_components/foundation-sites/js/foundation.equalizer.js',
'bower_components/foundation-sites/js/foundation.interchange.js',
'bower_components/foundation-sites/js/foundation.magellan.js',
'bower_components/foundation-sites/js/foundation.offcanvas.js',
'bower_components/foundation-sites/js/foundation.orbit.js',
'bower_components/foundation-sites/js/foundation.responsiveMenu.js',
'bower_components/foundation-sites/js/foundation.responsiveToggle.js',
'bower_components/foundation-sites/js/foundation.reveal.js',
'bower_components/foundation-sites/js/foundation.slider.js',
'bower_components/foundation-sites/js/foundation.sticky.js',
'bower_components/foundation-sites/js/foundation.tabs.js',
'bower_components/foundation-sites/js/foundation.toggler.js',
'bower_components/foundation-sites/js/foundation.tooltip.js',
'src/assets/js/**/!(app).js',
'src/assets/js/app.js'
]
};
// Delete the "dist" folder
// This happens every time a build starts
gulp.task('clean', function(done) {
rimraf('dist', done);
});
// Browser Sync wrapper task
// allows for proper injection of css files
gulp.task('reload', function(cb) {
browser.reload();
cb();
});
// Copy files out of the assets folder
// This task skips over the "img", "js", and "scss" folders, which are parsed separately
gulp.task('copy', function() {
return gulp.src(PATHS.assets)
.pipe(gulp.dest('dist/assets'));
});
// Copy page templates into finished HTML files
gulp.task('pages', function() {
return gulp.src('src/pages/**/*.{html,hbs,handlebars}')
.pipe(panini({
root: 'src/pages/',
layouts: 'src/layouts/',
partials: 'src/partials/',
data: 'src/data/',
helpers: 'src/helpers/'
}))
.pipe(gulp.dest('dist'));
});
gulp.task('pages:reset', function(cb) {
panini.refresh();
gulp.run('pages', cb);
});
gulp.task('styleguide', function(cb) {
sherpa('src/styleguide/index.md', {
output: 'dist/styleguide.html',
template: 'src/styleguide/template.html'
}, cb);
});
// Compile Sass into CSS
// In production, the CSS is compressed
gulp.task('sass', function() {
var uncss = $.if(isProduction, $.uncss({
html: ['src/**/*.html'],
ignore: [
new RegExp('^meta\..*'),
new RegExp('^\.is-.*')
]
}));
var minifycss = $.if(isProduction, $.minifyCss());
return gulp.src('src/assets/scss/app.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
includePaths: PATHS.sass
})
.on('error', $.sass.logError))
.pipe($.autoprefixer({
browsers: COMPATIBILITY
}))
.pipe(uncss)
.pipe(minifycss)
.pipe($.if(!isProduction, $.sourcemaps.write()))
.pipe(gulp.dest('dist/assets/css'))
.pipe(browser.reload({stream: true}));
});
// Combine JavaScript into one file
// In production, the file is minified
gulp.task('javascript', function() {
var uglify = $.if(isProduction, $.uglify()
.on('error', function (e) {
console.log(e);
}));
return gulp.src(PATHS.javascript)
.pipe($.sourcemaps.init())
.pipe($.concat('app.js'))
.pipe(uglify)
.pipe($.if(!isProduction, $.sourcemaps.write()))
.pipe(gulp.dest('dist/assets/js'));
});
// Copy images to the "dist" folder
// In production, the images are compressed
gulp.task('images', function() {
var imagemin = $.if(isProduction, $.imagemin({
progressive: true
}));
return gulp.src('src/assets/img/**/*')
.pipe(imagemin)
.pipe(gulp.dest('dist/assets/img'));
});
// Build the "dist" folder by running all of the above tasks
gulp.task('build', function(done) {
sequence('clean', ['pages', 'sass', 'javascript', 'images', 'copy'], 'styleguide', done);
});
// Start a server with LiveReload to preview the site in
gulp.task('server', ['build'], function() {
browser.init({
server: 'dist', port: PORT
});
});
// Build the site, run the server, and watch for file changes
gulp.task('default', ['build', 'server'], function() {
gulp.watch(PATHS.assets, ['copy', 'reload']);
gulp.watch(['src/pages/**/*.html'], ['pages', 'reload']);
gulp.watch(['src/{layouts,partials}/**/*.html'], ['pages:reset', 'reload']);
gulp.watch(['src/assets/scss/**/*.scss'], ['sass']);
gulp.watch(['src/assets/js/**/*.js'], ['javascript', 'reload']);
gulp.watch(['src/assets/img/**/*'], ['images', 'reload']);
gulp.watch(['src/styleguide/**'], ['styleguide', 'reload']);
});
Thanks you - Adolfo
I was helped with the fix at zurb/foundation-sites on github by gakimball. There were issues with the gulp.js file for foundation 6.1.1. Github issue page: https://github.com/zurb/panini/issues/10#issuecomment-172692241 explains more. Replacing my gulp.js file with the following code fixed the issue.
New gulp.js:
var $ = require('gulp-load-plugins')();
var argv = require('yargs').argv;
var browser = require('browser-sync');
var gulp = require('gulp');
var panini = require('panini');
var rimraf = require('rimraf');
var sequence = require('run-sequence');
var sherpa = require('style-sherpa');
// Check for --production flag
var isProduction = !!(argv.production);
// Port to use for the development server.
var PORT = 8000;
// Browsers to target when prefixing CSS.
var COMPATIBILITY = ['last 2 versions', 'ie >= 9'];
// File paths to various assets are defined here.
var PATHS = {
assets: [
'src/assets/**/*',
'!src/assets/{img,js,scss}/**/*'
],
sass: [
'bower_components/foundation-sites/scss',
'bower_components/motion-ui/src/'
],
javascript: [
'bower_components/jquery/dist/jquery.js',
'bower_components/what-input/what-input.js',
'bower_components/foundation-sites/js/foundation.core.js',
'bower_components/foundation-sites/js/foundation.util.*.js',
// Paths to individual JS components defined below
'bower_components/foundation-sites/js/foundation.abide.js',
'bower_components/foundation-sites/js/foundation.accordion.js',
'bower_components/foundation-sites/js/foundation.accordionMenu.js',
'bower_components/foundation-sites/js/foundation.drilldown.js',
'bower_components/foundation-sites/js/foundation.dropdown.js',
'bower_components/foundation-sites/js/foundation.dropdownMenu.js',
'bower_components/foundation-sites/js/foundation.equalizer.js',
'bower_components/foundation-sites/js/foundation.interchange.js',
'bower_components/foundation-sites/js/foundation.magellan.js',
'bower_components/foundation-sites/js/foundation.offcanvas.js',
'bower_components/foundation-sites/js/foundation.orbit.js',
'bower_components/foundation-sites/js/foundation.responsiveMenu.js',
'bower_components/foundation-sites/js/foundation.responsiveToggle.js',
'bower_components/foundation-sites/js/foundation.reveal.js',
'bower_components/foundation-sites/js/foundation.slider.js',
'bower_components/foundation-sites/js/foundation.sticky.js',
'bower_components/foundation-sites/js/foundation.tabs.js',
'bower_components/foundation-sites/js/foundation.toggler.js',
'bower_components/foundation-sites/js/foundation.tooltip.js',
'src/assets/js/**/!(app).js',
'src/assets/js/app.js'
]
};
// Delete the "dist" folder
// This happens every time a build starts
gulp.task('clean', function(done) {
rimraf('dist', done);
});
// Copy files out of the assets folder
// This task skips over the "img", "js", and "scss" folders, which are parsed separately
gulp.task('copy', function() {
return gulp.src(PATHS.assets)
.pipe(gulp.dest('dist/assets'));
});
// Copy page templates into finished HTML files
gulp.task('pages', function() {
return gulp.src('src/pages/**/*.{html,hbs,handlebars}')
.pipe(panini({
root: 'src/pages/',
layouts: 'src/layouts/',
partials: 'src/partials/',
data: 'src/data/',
helpers: 'src/helpers/'
}))
.pipe(gulp.dest('dist'))
.on('finish', browser.reload);
});
gulp.task('pages:reset', function(done) {
panini.refresh();
gulp.run('pages');
done();
});
gulp.task('styleguide', function(done) {
sherpa('src/styleguide/index.md', {
output: 'dist/styleguide.html',
template: 'src/styleguide/template.html'
}, function() {
browser.reload;
done();
});
});
// Compile Sass into CSS
// In production, the CSS is compressed
gulp.task('sass', function() {
var uncss = $.if(isProduction, $.uncss({
html: ['src/**/*.html'],
ignore: [
new RegExp('^meta\..*'),
new RegExp('^\.is-.*')
]
}));
var minifycss = $.if(isProduction, $.minifyCss());
return gulp.src('src/assets/scss/app.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
includePaths: PATHS.sass
})
.on('error', $.sass.logError))
.pipe($.autoprefixer({
browsers: COMPATIBILITY
}))
.pipe(uncss)
.pipe(minifycss)
.pipe($.if(!isProduction, $.sourcemaps.write()))
.pipe(gulp.dest('dist/assets/css'))
.pipe(browser.reload({ stream: true }));
});
// Combine JavaScript into one file
// In production, the file is minified
gulp.task('javascript', function() {
var uglify = $.if(isProduction, $.uglify()
.on('error', function (e) {
console.log(e);
}));
return gulp.src(PATHS.javascript)
.pipe($.sourcemaps.init())
.pipe($.concat('app.js'))
.pipe(uglify)
.pipe($.if(!isProduction, $.sourcemaps.write()))
.pipe(gulp.dest('dist/assets/js'))
.on('finish', browser.reload);
});
// Copy images to the "dist" folder
// In production, the images are compressed
gulp.task('images', function() {
var imagemin = $.if(isProduction, $.imagemin({
progressive: true
}));
return gulp.src('src/assets/img/**/*')
.pipe(imagemin)
.pipe(gulp.dest('dist/assets/img'))
.on('finish', browser.reload);
});
// Build the "dist" folder by running all of the above tasks
gulp.task('build', function(done) {
sequence('clean', ['pages', 'sass', 'javascript', 'images', 'copy'], 'styleguide', done);
});
// Start a server with LiveReload to preview the site in
gulp.task('server', ['build'], function() {
browser.init({
server: 'dist', port: PORT
});
});
// Build the site, run the server, and watch for file changes
gulp.task('default', ['build', 'server'], function() {
gulp.watch(PATHS.assets, ['copy']);
gulp.watch(['src/pages/**/*'], ['pages']);
gulp.watch(['src/{layouts,partials,helpers,data}/**/*'], ['pages:reset']);
gulp.watch(['src/assets/scss/**/{*.scss, *.sass}'], ['sass']);
gulp.watch(['src/assets/js/**/*.js'], ['javascript']);
gulp.watch(['src/assets/img/**/*'], ['images']);
gulp.watch(['src/styleguide/**'], ['styleguide']);
});
Thanks to the code above browser-sync is working again - Thanks gakimball!
I have an issue with wiredep: In my index.scss file, I have this block at the top:
/**
* Do not remove this comments bellow. It's the markers used by wiredep to inject
* sass dependencies when defined in the bower.json of your dependencies
*/
// bower:scss
// endbower
Also, I have installed a bower dependency, let's say color-dependency, which contains a couple files *.scss
The problem is that I can't see those files injected in my index.scss
Here is my gulp task for styles
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep').stream;
var _ = require('lodash');
gulp.task('styles', function () {
var sassOptions = {
style: 'expanded'
};
var injectFiles = gulp.src([
path.join(conf.paths.src, '/app/**/*.scss'),
path.join('!' + conf.paths.src, '/app/index.scss')
], { read: false });
var injectOptions = {
transform: function(filePath) {
filePath = filePath.replace(conf.paths.src + '/app/', '');
return '#import "' + filePath + '";';
},
starttag: '// injector',
endtag: '// endinjector',
addRootSlash: false
};
return gulp.src([
path.join(conf.paths.src, '/app/index.scss')
])
.pipe($.inject(injectFiles, injectOptions))
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe($.sourcemaps.init())
.pipe($.sass(sassOptions)).on('error', conf.errorHandler('Sass'))
.pipe($.autoprefixer()).on('error', conf.errorHandler('Autoprefixer'))
.pipe($.sourcemaps.write())
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app/')))
.pipe(browserSync.reload({ stream: true }));
});
I also had the same problem using the gulp generator but only with bootstrap-sass. I added the following to get bootstrap to work:
conf.js
exports.wiredep = {
exclude: [/\/bootstrap\.js$/, /\/bootstrap-sass\/.*\.js/, /\/bootstrap\.css/],
directory: 'bower_components'
};
bower.json
"overrides": {
"bootstrap-sass": {
"main": [
"assets/stylesheets/_bootstrap.scss",
"assets/fonts/bootstrap/glyphicons-halflings-regular.eot",
"assets/fonts/bootstrap/glyphicons-halflings-regular.svg",
"assets/fonts/bootstrap/glyphicons-halflings-regular.ttf",
"assets/fonts/bootstrap/glyphicons-halflings-regular.woff",
"assets/fonts/bootstrap/glyphicons-halflings-regular.woff2"
]
}
},
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']);
});