Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does gulp-livereload work with Gulp 4? #138

Open
epicserve opened this issue Sep 29, 2018 · 8 comments
Open

Does gulp-livereload work with Gulp 4? #138

epicserve opened this issue Sep 29, 2018 · 8 comments

Comments

@epicserve
Copy link

I haven't had any luck getting gulp-livereload to work with Gulp 4. I also don't see any Gulp 4 examples in the README.md.

@LimeWub
Copy link

LimeWub commented Nov 27, 2018

Not sure if you still need help with this.
I'm using it with Gulp 4 and it works fine; just pipe to livereload after every function you want to reload at (css and js in my case) and set it to listen in your watch task.

Attaching my current gulpfile.js in case it helps anyone :)

// package vars
const pkg = require("./package.json");

// gulp
const gulp = require("gulp");

// load all plugins in "devDependencies" into the variable _f
const _f = require("gulp-load-plugins")({
	pattern: ["*"],
	scope: ["devDependencies"]
});

const onError = (err) => {
	console.log(err);
};

const banner = [
	"/**",
	" * @project     <%= pkg.name %>",
	" * @author      <%= pkg.author %>",
	" * @build       " + _f.moment().format("llll") + " ET",
//	" * @release     " + _f.gitRevSync.long() + " [" + _f.gitRevSync.branch() + "]",
	" * @copyright   Copyright (c) " + _f.moment().format("YYYY") + ", <%= pkg.copyright %>",
	" *",
	" */",
	""
].join("\n");

// scss - build the scss to the build folder, including the required paths, and writing out a sourcemap
gulp.task("scss", () => {
	_f.fancyLog("-> Compiling scss");
	return gulp.src(pkg.paths.src.css + pkg.vars.scssName, { allowEmpty: true })
		.pipe(_f.plumber({errorHandler: onError}))
		.pipe(_f.sassGlob())
		.pipe(_f.sourcemaps.init({loadMaps: true}))
		.pipe(_f.sass({
                includePaths: pkg.paths.scss
			})
			.on("error", _f.sass.logError))
		.pipe(_f.cached("sass_compile"))
		.pipe(_f.autoprefixer(
		{
			browsers: ['last 2 versions', 'iOS >= 8']
		}
		))
		.pipe(_f.sourcemaps.write("./"))
		.pipe(_f.size({gzip: true, showFiles: true}))
		.pipe(gulp.dest(pkg.paths.build.css));
});

// css task - combine & minimize any distribution CSS into the public css folder, and add our banner to it
gulp.task("css", gulp.series("scss", () => {
	_f.fancyLog("-> Building css");
	return gulp.src([pkg.paths.build.css + "**/*.css", "!"+ pkg.paths.dist.css + "**/*"], { allowEmpty: true })
		.pipe(_f.plumber({errorHandler: onError}))
		.pipe(_f.print.default())
		.pipe(_f.sourcemaps.init({loadMaps: true}))
		.pipe(_f.concat(pkg.vars.cssName))
		.pipe(_f.cssnano({
			discardComments: {
				removeAll: true
			},
			discardDuplicates: true,
			discardEmpty: true,
			minifyFontValues: true,
			minifySelectors: true
		}))
		.pipe(_f.header(banner, {pkg: pkg}))
		.pipe(_f.sourcemaps.write("./"))
		.pipe(_f.size({gzip: true, showFiles: true}))
		.pipe(gulp.dest(pkg.paths.dist.css))
		.pipe(_f.filter("**/*.css"))
		.pipe(_f.livereload());
}));

// js task 
gulp.task("js", () => {
	_f.fancyLog("-> Building js");
	return gulp.src([pkg.paths.src.js + "**/*.js", "!"+ pkg.paths.dist.js + "**/*"], { allowEmpty: true })
        .pipe(_f.plumber({errorHandler: onError}))
        .pipe(_f.concat(pkg.vars.jsName))
		.pipe(_f.uglify())
		.pipe(_f.header(banner, {pkg: pkg}))
		.pipe(_f.size({gzip: true, showFiles: true}))
		.pipe(gulp.dest(pkg.paths.dist.js))
		.pipe(_f.filter("**/*.js"))
		.pipe(_f.livereload());
});

// Default task
gulp.task("default", gulp.series( "css", "js", () => {
	_f.livereload.listen();
	gulp.watch([pkg.paths.src.css + "**/*.scss", "!"+ pkg.paths.dist.css + "**/*"], gulp.series("css"));
    gulp.watch([pkg.paths.src.js + "**/*.js", "!"+ pkg.paths.dist.js + "**/*"], gulp.series("js"));
}));

@mycoolade
Copy link

Use same. like gulp@3

function html_make () {
    return src([path.source.template.root + '/**/*.html'].concat(path.ignore))
    .pipe(extender(rule.htmlExtend)) // default options
    .pipe(inlineCss(rule.inlineCss))
    .pipe(dest(path.devserver))
    .pipe(livereload({start:true}))
}

@columbian-chris
Copy link

I'm also having issues. Gulp 3.9.1 works just fine for me but not 4.0.0. It detects changes just fine when I edit a watched file via SSH (using Vagrant with Ubuntu 18.04) in a text editor, but no longer will it detect changes if I update a watched via my host in a synced folder.

Simplest example I can produce:

`const gulp = require('gulp'),
livereload = require('gulp-livereload');

gulp.task('watch', function(done){
livereload.listen(35729);
gulp.watch('example.php').on('change', function(file){
console.log('Change detected in file: ' + file);
});
done();
});`

Loads fine, and again, it detects changes when I make changes to a watched when I SSH into the Vagrant box, but no longer when I edit a file locally on my host machine outside of the Vagrant environment. Works totally fine when I revert Gulp to 3.9.1.

@columbian-chris
Copy link

Update: the same behavior occurs when I tried browsersync, so obviously this is not a livereload problem, it appears to be an issue with Gulp 4.0.

@jcklpe
Copy link

jcklpe commented May 2, 2019

I've tried browsersync in the past and found it to be too heavyweight for what I wanted to do. I'm doing a pretty simple SCSS, and vanilla HTML/JS project and I'm having trouble getting livereload to work. I've installed the chrome extension and it seems to be giving a "reloaded" message but it's not actually reloading the webpage I'm working on (or any other from what I can see).

Here's my gulpfile if anyone has any ideas. I'm using gulp 4 also:

// Gulp.js configuration
"use strict";

//source and build folders
const dir = {
  src: "./assets/src/",
  build: "./assets/build/",
  root: "./"
},
  // Gulp and plugins
  gulp = require("gulp"),
  gutil = require("gulp-util"),
  imagemin = require("gulp-imagemin"),
  sass = require("gulp-sass"),
  postcss = require("gulp-postcss"),
  // concat = require("gulp-concat"),
  stripdebug = require("gulp-strip-debug"),
  uglify = require("gulp-uglify"),
  sourcemaps = require("gulp-sourcemaps"),
  // babel = require("gulp-babel"),
  gulpImport = require("gulp-imports"),
  livereload = require('gulp-livereload');




//- CSS
//config
var css = {
  src: dir.src + "scss/*.scss",
  watch: dir.src + "scss/**/*.scss",
  build: dir.build,
  sassOpts: {
    outputStyle: "expanded",
    //   imagePath       : images.build,
    precision: 3,
    errLogToConsole: true,
    includePaths: ['scss/**/*.scss']

  },
  processors: [
    require("postcss-assets")({
      // loadPaths: ['images/'],
      basePath: dir.build,
      baseUrl: "/"
    }),
    require("autoprefixer")({
      browsers: ["last 2 versions", "> 2%"]
    }),
    require("css-mqpacker"),
    require("cssnano")
  ]
};

// CSS processing task
gulp.task("css", () =>
{
  return gulp
    .src(css.src)
    .pipe(sourcemaps.init())
    .pipe(sass(css.sassOpts))
    .pipe(postcss(css.processors))
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest(css.build))
    .pipe(livereload());
});

//-Javascript
//head config
const jshead = {
  src: dir.src + "js/head.js", //*/
  build: dir.build + "./",
  watch: dir.src + "js/**/*.js" //*/
};

// JS head processing task
gulp.task("jshead", function ()
{
  return gulp
    .src(jshead.src)
    .pipe(sourcemaps.init())
    .pipe(gulpImport())
    //.pipe(uglify())
    //.pipe(stripdebug())
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest(jshead.build))
    .pipe(livereload());
});

// footer config
const jsfooter = {
  src: dir.src + "js/footer.js", //*/
  build: dir.build + "./",
  watch: dir.src + "js/**/*.js" //*/
};

// JS footer processing task
gulp.task("jsfooter", function ()
{
  return gulp
    .src(jsfooter.src)
    .pipe(sourcemaps.init())
    .pipe(gulpImport())
    .pipe(uglify())
    .pipe(stripdebug())
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest(jsfooter.build));
});

gulp.task("js", ["jshead", "jsfooter"]);

//- Build
gulp.task("build", ["css", "js"]);

//- Watch

gulp.task("watch", () =>
{
  livereload.listen();
  gulp.watch(css.watch, ["css"]);

  gulp.watch(jshead.watch, ["jshead"]);

  gulp.watch(jsfooter.watch, ["jsfooter"]);


});

// default task
gulp.task("default", ["build", "watch"]);

//- Image Uploads optimization

gulp.task("image", () =>
  gulp
    .src("../../uploads/**/*")
    .pipe(
      imagemin({
        verbose: true
      })
    )
    .pipe(gulp.dest("../../uploads/"))
);

And here's a sample of my gulp cli readout:


[11:12:31] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/styles.css.map reloaded. 
[11:12:31] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/styles.css reloaded.
[11:12:31] Finished 'css' after 9.18 s
[11:15:52] Starting 'jshead'... 
[11:15:52] Starting 'jsfooter'...
[11:15:52] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js.map reloaded. 
[11:15:52] Finished 'jsfooter' after 218 ms
[11:15:52] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js reloaded.
[11:15:52] Finished 'jshead' after 228 ms 
[11:22:51] Starting 'jshead'... 
[11:22:51] Starting 'jsfooter'... 
[11:22:51] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js.map reloaded. 
[11:22:51] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js reloaded. 
[11:22:51] Finished 'jshead' after 668 ms
[11:22:51] Finished 'jsfooter' after 660 ms
[11:23:24] Starting 'jshead'... 
[11:23:24] Starting 'jsfooter'...
[11:23:24] Finished 'jsfooter' after 258 ms 
[11:23:24] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js.map reloaded.
[11:23:24] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js reloaded.
[11:23:24] Finished 'jshead' after 273 ms 
[11:23:44] Starting 'jshead'... 
[11:23:44] Starting 'jsfooter'...
[11:23:45] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js.map reloaded. 
[11:23:45] Finished 'jsfooter' after 287 ms
[11:23:45] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js reloaded. 
[11:23:45] Finished 'jshead' after 613 ms
[11:32:58] Starting 'jshead'... 
[11:32:58] Starting 'jsfooter'...
[11:32:59] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js.map reloaded. 
[11:32:59] Finished 'jsfooter' after 552 ms 
[11:32:59] /mnt/c/Users/aslan/home/work/Code/coa-dev-challenges/frontend/agnostic/assets/build/head.js reloaded.
[11:32:59] Finished 'jshead' after 562 ms

@vandres
Copy link

vandres commented Aug 23, 2019

For me to work, I had to separate the default and watch task and also call the tasks with gulp.series()

Before:

gulp.task('default', gulp.series(['css', 'js']), function() {
    livereload.listen();
    gulp.watch("./web/scss/**/*.scss", ['css']);
    gulp.watch("./web/js/footer/**/*.js", ['js']);
});

After

gulp.task('watch', function() {
    livereload.listen();
    gulp.watch("./web/scss/**/*.scss", gulp.series(['css']));
    gulp.watch("./web/js/footer/**/*.js",  gulp.series(['js']));
});

gulp.task('default', gulp.series(['css', 'js', 'watch']));

@mpltr
Copy link

mpltr commented Apr 24, 2020

For the .reload() method used to refresh the page, I found I had to use it in an async function after updating to Gulp 4:

gulp.watch(phpFiles, async () => livereload.reload() );

where php files is the directory to watch

@jcklpe
Copy link

jcklpe commented Apr 24, 2020

I actually recently fixed this issue for myself. If it would help anyone here is a link to my gulp file: https://github.com/jcklpe/common-wp-theme/blob/master/gulpfile.js

And here is it's contents.

// Gulp.js configuration
"use strict";

// options for src and build folders
const dir = {
    src: "./assets/src/",
    build: "./assets/build/",
    vendor: "./assets/vendor/",
    root: "./",
    // Replace with URL of your local site
    localDevURL: "dev-colab.test/"
  },
  // gulp plugins etc
  gulp = require("gulp"),
  gutil = require("gulp-util"),
  sass = require("gulp-sass"),
  cssnano = require("cssnano"),
  autoprefixer = require("gulp-autoprefixer"),
  sourcemaps = require("gulp-sourcemaps"),
  //NOTE: commenting this out because it's whining about something or other and I don't even use this thing. its another thing from a previous dev
//   jshint = require("gulp-jshint"),
//   stylish = require("jshint-stylish"),
  uglify = require("gulp-uglify"),
  concat = require("gulp-concat"),
  rename = require("gulp-rename"),
  plumber = require("gulp-plumber"),
  //NOTE: I have commented out bower because it's something left over from the previous dev and I don't really use the command that uses it and from what I can tell that command is better handled with npm but yeah that's it for now.
  // bower = require("gulp-bower"),
  babel = require("gulp-babel"),
  postcss = require("gulp-postcss"),
  browserSync = require("browser-sync").create();

// Browser-sync
var browsersync = false;

//- CSS
//config
var scss = {
  src: dir.src + "scss/*.scss",
  watch: dir.src + "scss/**/*.scss", //*/
  build: dir.build + "scss/",
  sassOpts: {
    outputStyle: "expanded",
    //   imagePath       : images.build,
    precision: 3,
    errLogToConsole: true
  },
  processors: [
    require("postcss-assets")({
      // loadPaths: ['images/'],
      basePath: dir.build
    }),
    require("autoprefixer")(),
    require("css-mqpacker"),
    require("cssnano")
  ]
};

// SCSS processing
gulp.task(
  "scss",
  gulp.series(() => {
    return gulp
      .src(scss.src)
      .pipe(sourcemaps.init())
      .pipe(sass(scss.sassOpts))
      .pipe(postcss(scss.processors))
      .pipe(sourcemaps.write("./"))
      .pipe(gulp.dest(scss.build))
      .pipe(
        browsersync
          ? browsersync.reload({
              stream: true
            })
          : gutil.noop()
      );
  })
);

//- Javascript
//config
var js = {
src: dir.src + "js/*.js",
watch: dir.src + "js/**/*.js",
foundation: dir.vendor + "foundation-sites/js/",
build: dir.build + "js/",
};

// concat and minify JavaScript
gulp.task(
  "site-js",
  gulp.series(() => {
    return gulp
      .src(js.src)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(concat("scripts.js"))
      .pipe(gulp.dest(js.build))
      .pipe(
        rename({
          suffix: ".min"
        })
      )
      .pipe(uglify())
      .pipe(sourcemaps.write(".")) // Creates sourcemap for minified JS
      .pipe(gulp.dest(js.build))
      .pipe(
        browsersync
          ? browsersync.reload({
              stream: true
            })
          : gutil.noop()
      );
  })
);

// concat, and minify Foundation JavaScript
gulp.task(
  "foundation-js",
  gulp.series(() => {
    return gulp
      .src([
        // Foundation core - needed if you want to use any of the components below
        dir.vendor + "foundation.cor*.js",
        dir.vendor + "foundation.util.*.js",

        // Pick the components you need in your project
        dir.vendor + "foundation.abid*.js",
        dir.vendor + "foundation.accordi*n.js",
        dir.vendor + "foundation.accordionMen*.js",
        dir.vendor + "foundation.dr*lldown.js",
        dir.vendor + "foundation.drop*own.js",
        dir.vendor + "foundation.dro*downMenu.js",
        dir.vendor + "foundation.equ*lizer.js",
        dir.vendor + "foundation.int*rchange.js",
        dir.vendor + "foundation.mage*lan.js",
        dir.vendor + "foundation.offca*vas.js",
        dir.vendor + "foundation.orb*t.js",
        dir.vendor + "foundation.res*onsiveMenu.js",
        dir.vendor + "foundation.respon*iveToggle.js",
        dir.vendor + "foundation.rev*al.js",
        dir.vendor + "foundation.sli*er.js",
        dir.vendor + "foundation.stick*.js",
        dir.vendor + "foundation.t*bs.js",
        dir.vendor + "foundation.t*ggler.js",
        dir.vendor + "foundation.tool*ip.js"
      ])
      .pipe(
        babel({
          presets: ["es2015"],
          compact: true
        })
      )
      .pipe(sourcemaps.init())
      .pipe(concat("foundation.js"))
      .pipe(gulp.dest("./assets/build/js"))
      .pipe(
        rename({
          suffix: ".min"
        })
      )
      .pipe(uglify())
      .pipe(sourcemaps.write(".")) // Creates sourcemap for minified Foundation JS
      .pipe(gulp.dest("./assets/build/js"));
  })
);

// Browser-Sync watch files and inject changes
gulp.task(
  "dev",
  gulp.series(() => {
    // Watch files
    var files = [
      "./assets/build/scss/*.css",
      "./assets/build/js/*.js",
      "**/*.php",
      "assets/images/**/*.{png,jpg,gif,svg,webp}"
    ];

    browserSync.init(files, {

      proxy: dir.localDevURL
    });

    //watch scss
      gulp.watch(scss.watch, gulp.series("scss"));

    // watch js
    gulp
      .watch("./assets/src/js/*.js", gulp.series("site-js"))
      .on("change", browserSync.reload);
  })
);

// Watch files for changes (without Browser-Sync)
gulp.task(
    "watch",
    gulp.series(() => {
        // Watch .scss files
        gulp.watch(["./assets/src/scss/**/*.scss"], gulp.series("scss"));

        // Watch site-js files
        gulp.watch("./assets/src/js/*.js", gulp.series("site-js"));
    })
);

// Run styles, site-js and foundation-js
gulp.task(
  "default",
    gulp.series("scss", "site-js", "foundation-js")

);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants