Coder Social home page Coder Social logo

gulp-livereload's Introduction

gulp-livereload

Build Status Code Climate Livereload downloads Tag MIT Licensed

A lightweight gulp plugin for livereload to be used with the livereload chrome extension or a livereload middleware.

Install

npm install --save-dev gulp-livereload

3.x Upgrade Notice

gulp-livereload will not automatically listen for changes. You now have to manually call livereload.listen unless you set the option start:

livereload({ start: true })

Usage

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload');

gulp.task('less', function() {
  gulp.src('less/*.less')
    .pipe(less())
    .pipe(gulp.dest('css'))
    .pipe(livereload());
});

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch('less/*.less', ['less']);
});

See examples.

API & Variables

Options (Optional)

These options can either be set through livereload.listen(options) or livereload(options).

port                     Server port
host                     Server host
basePath                 Path to prepend all given paths
start                    Automatically start
quiet        false       Disable console logging
reloadPage   index.html  Path to the browser's current page for a full page reload

livereload([options])

Creates a stream which notifies the livereload server on what changed.

livereload.listen([options])

Starts a livereload server. It takes an optional options parameter that is the same as the one noted above. Also you dont need to worry with multiple instances as this function will end immediately if the server is already runing.

livereload.changed(path)

Alternatively, you can call this function to send changes to the livereload server. You should provide either a simple string or an object, if an object is given it expects the object to have a path property.

NOTE: Calling this function without providing a path will do nothing.

livereload.reload([file])

You can also tell the browser to refresh the entire page. This assumes the page is called index.html, you can change it by providing an optional file path or change it globally with the options reloadPage.

livereload.middleware

You can also directly access the middleware of the underlying server instance (mini-lr.middleware) for hookup through express, connect, or some other middleware app

livereload.server

gulp-livereload also reveals the underlying server instance for direct access if needed. The instance is a "mini-lr" instance that this wraps around. If the server is not running then this will be undefined.

Debugging

Set the DEBUG environment variables to * to see what's going on

$ DEBUG=* gulp <task>

License

The MIT License (MIT)

Copyright (c) 2014 Cyrus David

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

gulp-livereload's People

Contributors

arnaudrinquin avatar bigtiger avatar cyrusdavid avatar demurgos avatar elwayman02 avatar generalov-epm avatar lancedikson avatar lukehorvat avatar pataar avatar psi-4ward avatar spxiaomin avatar zbennett10 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gulp-livereload's Issues

How to filter so that only changed files trigger the reload

Given the following task:

// Compile Our Coffee
gulp.task('coffee', function () {
  gulp.src( options.COFFEE_SOURCE )
    .pipe(changed( options.COFFEE_BUILD ))
    .pipe(coffee({
      bare: true,
      sourceMap: true
      })
    .on('error', gutil.log))
    .pipe(gulp.dest( options.COFFEE_BUILD ))
    .pipe(livereload());
});

When I save a coffee in the source folder all of the compiled files in the build folder get refreshed.

Btw, my watch task looks like this:

gulp.task('watch', function () {
  // server = livereload();
  gulp.watch(options.HTML_SOURCE, ['html']);
  gulp.watch(options.COFFEE_SOURCE, ['coffee', 'lint']);
  gulp.watch(options.SASS_SOURCE, ['sass']  );
});

Is there a way to configure the plugin so that only the changed files are refreshed?

Where did livereload.js go?

Just updated from v2.1.1 to v3.2.0.

I was relying on livereload.js, provided at "//[server]:35729/livereload.js", for a remote connection. But since updating, the javascript file has disappeared.

Is the javascript file still provided by gulp-livereload? Is there a better way to use livereload remotely? (The Chrome plugin seems restricted to localhost.)

Static Server Example not working

Hello -

I am trying to use gulp-livereload with a static server and I am not able to accomplish that. I have a site setup in my HOSTS file served via Nginx. I would like to use livereload to refresh my site when I make changes.

I am having problems with the server gulp task. It requires connect (btw: it is not listed as a dependency on your npm site). So I installed it: npm install connect
I am assuming that this is the connect git repo https://github.com/senchalabs/connect. When I execute the server task I get an error basically saying that connect "has no 'static' method".

Questions:

  1. Can I use live reload with nginx?
  2. If yes, can someone take a look at the server task and see what should be happening when I execute server.use(connect.static(dest)).listen(process.env.PORT || 80, next)

Thanks,

Jordan

refresh page on html change

Hi there,

First off, thanks for the plugin!

Quick question: how would you go about making the page refresh in case an html file has been changed?

cheers,

Otto

Add host parameter

I can't use gulp-livereload with mobile devices, because lr server binds to 127.0.0.1 but not 0.0.0.0.
Maybe I can specify 0.0.0.0 address somehow (for now I see only port parameter that I can pass with livereload.listen call)? Or it is not possible in current implementation?

how to make it play nice with nodemon?

I have a fullstack app with node/express on the backend, and I have a task to start the whole thing up using gulp-nodemon like so:

var reload = plugins.livereload();

gulp.task('nodemon', function() {
  plugins.nodemon({
    script: './src/server/bin/www',
    verbose: true,
    env: { 'NODE_ENV': 'development' },
    watch: './src/server',
    ext: 'js jade html css styl json',
    nodeArgs: ['--debug']
  }).on('restart', function () {
    // FIXME livereload -- this kills the browser session
    reload.changed('/');
  });
});

The livereload side works when the client files change. I'm just piping the tasks that change to the livereload plugin, and when they change, the browser refreshes as expected.

The server side works -- at least to restart the server. When nodemon detects a change in the server code, it kills and restarts the server.

Unfortunately, I can't get them both to play nicely together. I tried above to trap into the restart event for nodemon, and just tell the plugin that the index changed, but what happens (in Chrome at least) is that the page is replaced immediately with Chrome's No data received error. If I manually reload it, it comes up, so it appears to be a timing issue.

I was wondering if there is a recommended way to resolve this issue?

Add an option for silent mode

For user who also using *-lint tools, a long list of *file reloaded when init gulp is unbearable. Accepting an option to mute gutil.log would make it better.

Livereload after express restart

Hi,

I have the following configuration that triggers livereload on file change:

gulp.watch( [ 'server/*.js', 'config.json' ], [ 'server:restart' ] ).on('change', livereload.changed);

Howerver mostly this happens before server:restart finished, so Chrome shows me "The webpage is not available". Is there anyway to run livereload update after server restart?

when there's no parameter

If there's no port or server passed to liveload()

there will be an error:

... Uhoh. Got error listen EADDRINUSE ...
Error: listen EADDRINUSE

Error on livereload.js

Hello.

I have a problem on new version gulp-livereload. When I edit file and save him, gulp initializes reload page, but page don't reloaded, because livereload.js can not be executed due to an internal error:

Uncaught TypeError: Cannot read property 'match' of undefined  livereload.js:503

Alt text

test gulpfile.js

var gulp = require('gulp'),
    livereload = require('gulp-livereload');

gulp.task('livereload', function() {
    livereload.changed();
});

gulp.task('watch', function() {
    livereload.listen();
    gulp.watch('./**/*.html', ['livereload']);
});

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

gulp-livereload v2.1.1 worked well

Thanks for any help :)

Force full page reload

Any way to do this? When I have server files change livereload doesn't care because none of them are on the page, but I still want to reload the entire page

HTTPS?

Is there any way to make the LR server handle HTTPS requests?

Equivalent for refresh on change

Hi,

Can you tell me the equivalent code for the new version of gulp-livereload :

var server = livereload();
  gulp.watch(dest + '/**').on('change', function(file) {
      server.changed(file.path);
  });

When i use it i take this error message :

server.changed(file.path);
-----------^
TypeError: Object # has no method 'changed'

How can i solve it ?

Thanks

Change listening port and server Gulp livereload

I want to change the port and server my Gulp file is listening to using gulp-livereload.

The documentation is a bit hazy and I am not clear on the syntax, but here is my code:

var gulp         = require('gulp'),
    watch        = require('gulp-watch'),
    livereload   = require('gulp-livereload');


gulp.task('watch', function() {
    livereload.listen();
    gulp.watch('./css/**/*.css').on('change', livereload.changed);
    gulp.watch('./js/**/*.js').on('change', livereload.changed);
    gulp.watch('./blog/**/*.php').on('change', livereload.changed);
    gulp.watch('./**/*.php').on('change', livereload.changed);
});

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

And I want to change it so it is listening on port 4000, and server 0.0.0.0.

livereload.listen();

But I am not sure what to?

The reason I need this is to work with the Codio restricted ports.

Cheers.

Update

Using livereload.listen(4000); I now receive this message in terminal:

[21:41:25] Using gulpfile ~/workspace/Gulpfile.js                                                                                                                                                     
[21:41:25] Starting 'watch'...                                                                                                                                                                        
[21:41:26] Finished 'watch' after 395 ms                                                                                                                                                              
[21:41:26] Starting 'default'...                                                                                                                                                                      
[21:41:26] Finished 'default' after 8.9 μs                                                                                                                                                            
[21:41:26] Live reload server listening on: 4000                                                                                                                                                      
[21:41:29] index.php was reloaded.                                                                                                                                                                    
[21:41:29] Live reload server listening on: 35729                                                                                                                                                     
[21:41:30] index.php was reloaded. 

As you can see as soon as the first file is modified it switches back to the old port:

[21:41:26] Live reload server listening on: 4000                                                                                                                                                      
[21:41:29] index.php was reloaded.                                                                                                                                                                    
[21:41:29] Live reload server listening on: 35729                                                                                                                                                     
[21:41:30] index.php was reloaded. 

Any idea how to get this to stick?

Version mismatch causes type checking to fail

I was previously passing a tinylr.Server instance to gulp-livereload and everything was working fine.

At some point, I did something where I updated the dependencies in my project and ended up with my package.json specifying:

{
  "gulp-livereload": "^2.1.0",
  "tiny-lr": "^0.0.7"
}

Since gulp-livereloadat this version specified to use ^0.1.0, the gulp-livereload got its own copy of tiny-lr when doing an npm install.

Therefore, the instance that I created in my gulpfile.js did not pass the checks within the codebase that server instanceof tinylr.Server.

There are a few ways that this could be addressed:

  1. Duck typing instead of using instanceof to check if it's a tinylr.Server
  2. Exposing tinylr via the module.exports so that users of this plugin can create compatible instance (I don't really like this idea).
  3. Change the specification in the package.json to be more relaxed, so that the projects end up with the same copy of the module. I think this would be something like ^0.1.0 || < 0.1.0, but you may want specify a lower bound.
  4. Perhaps another way that I'm not thinking of.

Happy to send in a PR if you let me know which way would be best in your mind to address it.

Not reloading

If I use a port other than the default one, the page stops reloading automatically.
How can I solve this? Any help would be appreciated.

 gulp
 [16:25:14] Using gulpfile ~/Projects/node-project/gulp-examples/gulpfile.js
 [16:25:14] Starting 'default'...
 [16:25:14] Finished 'default' after 120 ms
 [16:25:14] Live reload server listening on: 35731
 [16:25:23] test.html was reloaded.
 [16:25:23] Live reload server listening on: 35729

[Question] would this way be more efficient than using gulp.watch?

Based on @vohof's snippet from a week or so ago, would this way be more efficient than using gulp.watch?

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    sass = require('gulp-ruby-sass'),
    prefix = require('gulp-autoprefixer'),
    minifyCSS = require('gulp-minify-css'),
    rename = require('gulp-rename'),
    notify = require('gulp-notify'),
    clean = require('gulp-clean');

var livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    server = lr(),
    lrport = 35729;

var paths = {
    images: [
        './img',
        '!./img/stock/*'],
    js: './js/*.js',
    js_compiled: './js/compiled',
    css: './css/scss/*.scss',
    css_compiled: './css/compiled',
    html: './*.html'
};

gulp.task('listen', function(next) {
    server.listen(lrport, function(err) {
        if (err) return console.error(err);
        next();
    });
});

gulp.task('html', ['listen'], function() {
    gulp.src(paths.html, {read: false})
        .pipe(watch())
        .pipe(livereload(server))
        .pipe(notify({
            message: 'Markup updated'
        }));
});

gulp.task('styles', ['listen'], function() {
    gulp.src(paths.css)
        .pipe(watch())
        .pipe(sass({
            style: 'expanded',
            lineNumbers: true
        }))
        .pipe(gulp.dest(paths.css_compiled))
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifyCSS())
        .pipe(livereload(server))
        .pipe(gulp.dest(paths.css_compiled))
        .pipe(notify({ message: 'Styles task complete' }));
});

gulp.task('scripts', ['listen'], function() {
    gulp.src(paths.js)
        .pipe(watch())
        .pipe(browserify())
        .pipe(concat('all.js'))
        .pipe(gulp.dest(paths.js_compiled))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(livereload(server))
        .pipe(gulp.dest(paths.js_compiled))
        .pipe(notify({ message: 'Scripts task complete' }));
});

gulp.task('default', function() {
    gulp.start('scripts', 'styles', 'html');
});

Change not triggered on nodemon restart

var nodemon = require('gulp-nodemon')
var livereload = require('gulp-livereload');

gulp.task('app:start', function () {
  var reload =  require('gulp-livereload')();
  nodemon({
    script: './config/boot.js',
    ext: 'js json coffee css less scss html'
  }).on('restart', function() {
    console.log("RESTARTED");
    reload.changed()
  })
})

The browser is not reloading but I see the [xx:xx:xx] * was reloaded. and RESTARTED in the console.

changed() method not causing refresh on browser

UPDATE:
I downgraded to "^2.1.0" and the issue resolved itself.

A change is successfully being detected with gulp.watch(), but I can not get the client front side browser to refresh with the changed() method. I see in the network tab that the livereload.js is successfully being injected into browser and there is a successful live socket session for livereload.

    var http = require('http');
    var connect = require('connect');
    var gulp = require('gulp');
    var livereload = require('connect-livereload');
    var refresh  = require('gulp-livereload');
    var serveStatic = require('serve-static');


    // Run Connect server
    var lrport = 35729;
    var server = connect();

     server.use(livereload({ port: lrport }));
    server.use(serveStatic('./app'));

    var PORT=9000;
    var HOST=["14.30.26.1"];

    function watch() {
        var watcher = gulp.watch(['./app/*']);
        watcher.on('change', function(event) {

        //SHOULD CAUSE REMOTE BROWSER REFRESH, BUT DOESN'T
        refresh.changed();

        console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
        });
    }

    gulp.task('connect', function () {
        // Start webserver
        require('http').createServer(server)
            .listen(PORT, HOST)
            .on('listening', function () {
                console.log('Darins server running on port ' + PORT);
            });
        // Start live reload
        refresh.listen(lrport);
        watch();
    });

Pattern to only reload CSS?

Is there a pattern to reload CSS only? Currently the entire page refreshes when CSS is changed. I believe tiny-lr supports events like the following: reload-js, reload-css, etc

Got error listen EADDRINUSE

I'm trying to solve a problem in a repository that uses gulp-livereload.

A few days ago I'm getting this error:

... Uhoh. Got error listen EADDRINUSE ...
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Server.listen (/Applications/MAMP/htdocs/conferencia-orlando/site/node_modules/gulp-livereload/node_modules/tiny-lr/lib/server.js:138:15)
at Function.exports.listen (/Applications/MAMP/htdocs/conferencia-orlando/site/node_modules/gulp-livereload/gulp-livereload.js:68:12)
at Function.exports.changed (/Applications/MAMP/htdocs/conferencia-orlando/site/node_modules/gulp-livereload/gulp-livereload.js:88:20)
at Transform.reload._transform (/Applications/MAMP/htdocs/conferencia-orlando/site/node_modules/gulp-livereload/gulp-livereload.js:24:13)
at Transform._read (_stream_transform.js:179:10)
at Transform._write (_stream_transform.js:167:12)

Here is the gulpfile.js:
https://github.com/samwx/html-skeleton-gulp/blob/master/gulpfile.js

How can I solve? Thanks.

Tiny-LR

installation fail

muse:NewBlog:% npm install gulp-livereload --save-dev                                                                                                         <master ✗>
npm ERR! Error: ENOENT, chmod '/home/vrtak-cz/Workspace/Vrtak-CZ/NewBlog/node_modules/gulp-livereload/node_modules/tiny-lr/bin/tiny-lr'
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR!     <http://github.com/npm/npm/issues>

npm ERR! System Linux 3.16.1-1-ARCH
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "gulp-livereload" "--save-dev"
npm ERR! cwd /home/vrtak-cz/Workspace/Vrtak-CZ/NewBlog
npm ERR! node -v v0.10.31
npm ERR! npm -v 1.4.27
npm ERR! path /home/vrtak-cz/Workspace/Vrtak-CZ/NewBlog/node_modules/gulp-livereload/node_modules/tiny-lr/bin/tiny-lr
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/vrtak-cz/Workspace/Vrtak-CZ/NewBlog/npm-debug.log
npm ERR! not ok code 0

i think because mklabs/tiny-lr@d5e74d3

Fix package.json

I think this is fixed already but unpublished. When using 1.4.1 i get this error

Cannot find module 'tiny-lr-fork'

since the top of livereload.js looks like this

  var gutil = require('gulp-util'),
      path = require('path'),
      tinylr = require('tiny-lr-fork'),

but you have tiny-lr in the package.json

options.auto: false prevents manual start without override

Example adaption of readme sample:

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload');

gulp.task('less', function() {
  return gulp.src('less/*.less')
    .pipe(less())
    .pipe(gulp.dest('css'))
    .pipe(livereload({ auto: false }));
});

gulp.task('watch', ['less'], function() {
  livereload.listen(); // gets caught
  gulp.watch('build/**', ['less']);
});

So if livereload({auto: false}) is invoked first, the server never starts. It can be fixed by using livereload.listen({auto: true}), but it seems weird that this is persisted across calls.

New syntax, livereload() doesnt seem to work

Connect the live reload

    gulp.task('watch', function() {
      livereload.listen();
      gulp.watch('static/scss/**/*.*', ['css']);
      gulp.watch('templates/**/*.*', ['css']);
      gulp.watch('static/js/**/*.js', ['css']);
      gulp.watch('**/*.py', ['css']);
    });

Propagate changes

    gulp.task('css', function() {
      gulp.src('static/scss/*.scss')
      .pipe(compass({
        config_file: './config.rb',
        sass: 'static/scss',
        css: 'dist/styles'
      }))
      .pipe(autoprefixer())
      .pipe(minifyCSS())
      .pipe(gulp.dest('dist/styles'))
      .pipe(livereload());
    });

The livereload() is called, but doesn't seem to trigger a reload of the browser. It worked with the old syntax using .on('changed') events.

livereload not reloading the browser at all

Hello,
I've put together an ultra small set of files (found here: http://dev.reintroducing.com/livereload.zip) that demonstrates livereload not working at all. When you download the folder just cd into it and run npm install then run gulp.

You will see a blank page (that's fine). Open up js/app.js and change the log on line 11 to whatever you'd like. In terminal you will see that main.js is refreshed but the page itself doesn't refresh. Same thing if you make any sass changes.

In the gulp/tasks folder you will see watch.js which defines the watch task. There you can also see browserify.js which runs browserify which has a pipe to livereload() at the end. Again, same applies for the sass in compass-dev.js which is run whenever any sass file is changed.

I've followed all the directions but this doesn't seem to work. I'm using Chrome on OSX Mavericks with the latest version of node. Any help would be greatly appreciated.

Rework API

First of all thanks for your package and all the effort you put into building it. I still have a suggestion concerning the usage API. I think it's kinda laborious that in order to use your package that I have to require multiple packages such as tiny-lr and instantiate a server on my own. I guess it would be easier to use if this process takes place "behind the scenes".

I'd rather want to use the plugin like this:

gulp.src('less/*.less')
    .pipe(watch())
    .pipe(less())
    .pipe(gulp.dest('css'))
    .pipe(livereload(35729));

Please let me know what you think about that. Cheers

Usage with gulp.watch()

Given the task

gulp.task('watch', ['default'], function () {
    gulp.watch(paths.src.js,   ['jshint']);
    gulp.watch(paths.src.css,  ['sass']);
});

It would be lovely to be able somehow to plug gulp-livereload (livereload()) there, without touching the inner tasks their selves (jshint, sass) - Do you think this could be possible?

.watch() doesn't return a pipe, but an EventEmitter object, which on change returns a data object containing the path of the modified / added / deleted file.

So far, I can think of only two "solutions":

  1. Add .pipe(livereload()) to every children task.
  2. Do gulp.watch(path.src.root, 'all') where all is the task that calls to both jshint and sass, and root is a glob with **/*

But it would be quite lovely to be able to trigger somehow "hey X file changed." (something like exposing server.changed maybe?)

I don't really know how this all messes with streams... What do you think?

missing info

there is a line in gulp-livereload.js

gutil.log(magenta(path.basename(filePath)) + ' was reloaded.');

in case the project has a complicated structure with a lot of dirs and files looking on the output [15:38:41] index.js was reloaded. it's not clear which exact index file (one of a dozen) was reloaded.
as a solution I can suggest just to dump full filePath as it is without trimming
or it's possible to subtract the project main dir from it with the help of process.cwd()

gulp-livereload seem lose files

It seems that gulp livereload lose images when listening.

Here is my gulpfile, I need to move my images to another directory, but some images will lost when refresh is on:

When I only do the move:

gulp.task('build-img', function() {
  return gulp.src(['fe/img/**/*.png',
                   'fe/img/**/*.gif',
                   'fe/img/**/*.jpg'])
             .pipe(gulp.dest('static/build/img'))
});

The results goes right:

img
├── index
│   ├── rec_sun.jpg
│   ├── right_arrow.png
│   └── user
│       ├── a1.jpg
│       ├── a10.jpg
│       ├── a11.jpg
│       ├── a12.jpg
│       ├── a13.jpg
│       ├── a14.jpg
│       ├── a15.jpg
│       ├── a16.jpg
│       ├── a17.jpg
│       ├── a18.jpg
│       ├── a19.jpg
│       ├── a2.jpg
│       ├── a3.jpg
│       ├── a4.jpg
│       ├── a5.jpg
│       ├── a6.jpg
│       ├── a7.jpg
│       ├── a8.jpg
│       └── a9.jpg
├── logo.png
├── mine
│   ├── finished.png
│   └── ongoing.png
└── misc
    └── my-account.png

Then add livereload:

var refresh = require('gulp-livereload');
gulp.task('build-img', function() {
  return gulp.src(['fe/img/**/*.png',
                   'fe/img/**/*.gif',
                   'fe/img/**/*.jpg'])
             .pipe(gulp.dest('static/build/img'))
             .pipe(refresh())  //add this line
});

Some images lost:

img
├── index
│   ├── rec_sun.jpg
│   ├── right_arrow.png
│   └── user
│       ├── a1.jpg
│       ├── a10.jpg
│       ├── a11.jpg
│       ├── a12.jpg
│       ├── a13.jpg
│       ├── a14.jpg
│       ├── a15.jpg
│       ├── a16.jpg
│       ├── a17.jpg
│       ├── a18.jpg
│       ├── a19.jpg
│       ├── a2.jpg
│       ├── a3.jpg
├── logo.png
├── mine
│   ├── finished.png
│   └── ongoing.png
└── misc
    └── my-account.png

It's not the very same result every time, this is the minimum code, so I think there is something wrong with the gulp-livereload.

I remembered that gulp-rev some time has the same issue, but been a little while, it does not show up again.

gulp-livereload and https

I'm sorry but I don't find a way to make it work. Can you explain a bit more about it?

Thank you very much.

Reloading all linked stylesheets, instead of one sent via websocket notification

livereload.js is unable properly match stylesheet to be reloaded, due to backslashes used as uri segments separators inside websocket notification. As a result, all stylesheets declared inside tag are being fetched.

Replacing all backslashes with forward slashes fixes issue.

module.exports = function (server) {
  var map = require('map-stream');

  var changed = function (file, cb) {   
    server.changed({
      body: {
        files: [file.path.replace(/\\/g,'/')]
        /* files: [file.path] */
      }
    });

    cb(null, file);
  };

  return map(changed);
};

Some screens made while debugging livereload.js:
Before slash replacement

image
After fix

image

Execution time

Most of the execution time in my gulp tasks is in minification. For example, using styles task below with a mid-size sass project, CSSO increases execution time from ~500ms to ~2.25s.

I'm writing both an expanded and a minified css file to disk and referencing the expanded file in development. I'd like livereload to refresh as soon as the expanded file is updated, however with the configuration below it waits for the whole task to finish before the browser updates.

var gulp = require('gulp');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var livereload = require('gulp-livereload');
var csso = require('gulp-csso');
var rename = require('gulp-rename');

gulp.task('styles', function() {
  return gulp.src('./src/stylesheets/*.scss')
    .pipe(sass())
    .pipe(prefix("last 2 version"))
    .pipe(gulp.dest('./build/assets/stylesheets'))
    .pipe(livereload())
    .pipe(csso())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./build/assets/stylesheets'));
});

Similarly, a watch task on my build directory also waits for the entire task to complete (both files written to disk) before updating the browser:

gulp.task('watch', function() {
  var server = livereload();

  var reload = function(file) {
    server.changed(file.path);
  };

  gulp.watch('src/javascripts/**', ['scripts']);
  gulp.watch('src/stylesheets/**', ['styles']);
  gulp.watch('src/images/**', ['images']);
  gulp.watch(['build/**']).on('change', reload);
});

Am I using livereload incorrectly to accomplish this?

livereload resets folded lines in sublime text 3

HI I have win 7/64bit, and I use sublime text 3 also 64 bits. When I save file, while there are folded lines it reopen them. This happens every time when I save file. It's a livereload plugin for chrome and I'm using gulp-livereload node module.

Install problem : host Windows max file path length exceeded

Hello,

I developp with Vagrant/Virtualbox and when I try to install gulp-livereload, I have a "mkdir error", cannot create folder because filepath length exceeds windows limits.

Is there any reasons why the folder tree is so deep or could it be reorganized a different way ?

Anyway thanks for the plugin :)

Xavier

Livereload after less()

Hi,

In documentation you have a sample how to use gulp.watch with less. I tried in the following configuration:

gulp.watch( [ 'www/**/*.less' ], [ 'less' ] ).on('change', livereload.changed);

and basically livereload runs before less is compiled into CSS.

// less
gulp.task('less', function () {
    gulp.src('www/less/style.less')
        .pipe(less({
            paths: [ path.join(__dirname, 'bower_components') ]
        }))
        .on('error', function (error) {
            gutil.log(gutil.colors.red('[' + error.plugin + '] ' + error.type + ' error: ' + error.message));
        })
        .pipe(gulp.dest('www/css'));
});

auto start issue

Hi,

I disable autostart by overriding livereload.options to avoid any utility tasks (like css) to run lr when it's not desired.

livereload.options.auto = false;

But then livereload.listen() won't start lr server until { auto: true } passed along.

Would be nice if livereload.listen() would explicitly start server regardless auto flag.

exports.changed + some sugar ideas

Would prevent a little overhead of constructing a stream every time a file changes.

Example:

gulp.watch(paths.tests, function(e){
  lr().changed(e.path);
});

would become

gulp.watch(paths.tests, function(e){
  lr.changed(e.path);
});

If you added a little sugar to the lr.changed function to accept objects with a path key you could simplify it even more.

gulp.watch(paths.tests, lr.changed);

Make livereload only start when needed?

var cond = require('gulp-cond');
var isDev = function(){ environment == "dev" }

gulp.task ...
.pipe(cond(isDev(), livereload()))

This should only run the function that livereload() returns when isDev() is true. In other words, if environment == production, completely ignore this line. However, in a production environment, the lr server will start, but not update itself. This is because you're starting the server immediately on the first function call [1].

How about pushing the server.listen() code into the reload.changed hook [2]? This would only start the server when it's actually needed.

edit: for anyone else encountering this, you can probably just do a plain conditional:

var pipes = gulp.src().pipe().pipe()
if (env == "dev") { pipes.pipe(livereload()) }

[1] https://github.com/vohof/gulp-livereload/blob/master/gulp-livereload.js#L20-L33
[2] https://github.com/vohof/gulp-livereload/blob/master/gulp-livereload.js#L35

Livereload server doesn't seem to start

I am using the basic syntax given, but when I attempt to connect to the livereload server it says that it is not running, and nmap seems to confirm this.

gulp.task 'styles', ->
    gulp.src(['./public/include/less/**/*.less', '!./**/_*.less'])
    .pipe plumber()
    .pipe less()
    .pipe gulp.dest('./public/include/css')
    .pipe livereload()

gulp.task 'watch', ['styles'], ->
    livereload.listen()

    gulp.watch './public/include/less/**/*.less', ['styles']

wait until task on watch is done

Is it possible to wait until tasks on gulp.watch are done to reload server?

right now I am using a settimeout, because my dev task takes about 4 seconds.

that make sense?

var server = livereload();
var watcher = gulp.watch(['./src/**/*.html','./src/**/*.css','./src/**/*.js','!./src/bower/**'],['dev']);
    watcher.on('change', function(file) {
        setTimeout(function(){server.changed(file.path);},5000);
    });

Discussion: better integration with gulp.watch

First of all - thank you!

Firstly, thnx for all the work put into this plugin, much appreciated.

The problem

Recently I'm using it on more and more projects and while playing with larger code-bases I've noticed that live-reload didn't pick all the changes / kicked with my initial setup, suggested in the docs:

gulp.watch('foo/**.js', ['bar', 'baz']).on('change', livereload.changed);

So, I was essentially bumping into the same issue as described in #17

A (partial) solution

Following the advice in the comment (#17 (comment)) I've switched to watching the destination folder:

gulp.watch('./dest/**').pipe(livereload.changed);

This solved the problem of missed reloads but introduced another one - multiple reloads for one file save. On top of this here we are watching both the sources and the destination folder, which is wasteful.

The (ultimate) solution?

Since I wasn't entirely happy with the current situation I've started to dig into ways of detecting end events of dependent tasks and it looks like Orchestrator is emitting task_start and task_stop events (https://github.com/orchestrator/orchestrator/blob/18831d3db0448910d49208d790256dc879b8e9e6/index.js#L284) when a given task starts / stops. So I was toying with the idea of adding a new method (not sure about the name, yet) to the livereload plugin, something along those lines:

livereload.forTasks(['bar', 'baz']);

This method would subscribe to tasks start / end events and trigger live-reload when all the tasks are done. The alternative method signature could look like:

livereload.forTasks({
  bar: 'src/static/*.css',
  baz: '**/*.js'
});

to support more precise tasks reloads.

Would be grateful for any feedback - I'm not sure if the above proposal is the best approach to solving the problem, but at least I hope that the underlying issue is clear.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.