GithubHelp home page GithubHelp logo

connect-livereload's People

Contributors

agrberg avatar andineck avatar eirikurn avatar guifromrio avatar hiroagustin avatar jack12816 avatar joshperry avatar msheakoski avatar nitinhayaran avatar pdehaan avatar sheenobu avatar sindresorhus avatar sparrowjang avatar stevemao avatar wearhere avatar woodne avatar xudejian avatar yankee42 avatar zoxon 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

connect-livereload's Issues

TypeError: Cannot read property 'split' of undefined

TypeError: Cannot read property 'split' of undefined
   at Object.livereload [as handle] (/home/michael-heuberger/code/videomail-client/node_modules/connect-livereload/index.js:91:49)
   at next (/home/michael-heuberger/code/videomail-client/node_modules/connect/lib/proto.js:174:15)
   at Function.app.handle (/home/michael-heuberger/code/videomail-client/node_modules/connect/lib/proto.js:182:3)
   at Http2SecureServer.app (/home/michael-heuberger/code/videomail-client/node_modules/connect/lib/connect.js:67:37)
   at emitTwo (events.js:131:20)
   at Http2SecureServer.emit (events.js:214:7)
   at Http2SecureServer.onServerStream (internal/http2/compat.js:710:10)
   at emitMany (events.js:147:13)
   at Http2SecureServer.emit (events.js:224:7)
   at ServerHttp2Session.sessionOnStream (internal/http2/core.js:2304:17)

Using "gulp-connect": "5.2.0" here

Corrupting non-html content

When livereload middleware is installed I'm finding that non-html content such as generated PDFs are being corrupted. I believe this is because livereload is trying to inject the reload script snippet into the content.

I notice that the code currently checks the request accept header however wouldn't it be more appropriate to check the response content-type header before injecting the script instead?

How to server a structure like app, app/components and /dist

Hi, I've set my connect.static to /dist and connect.directory to /app and I have a structure like this:

/Gulpfile.js (root with config files etc.)
/app (index.html as well as uncompiled scripts and styles go here)
/app/components (third party)
/dist (compiled assets go here)

How do you best make set it up to serve files from both app, dist (live compiled things) and the app/components folder?

Now I can only access files from one directory, the /dist. Should my build script copy all things that otherwise wouldn't need preprocessing to /dist as well as the things I compile? Seems over complicated to copy everything all the time.

Loosing of custom yeoman config on reload

I'm overriding yeomanConfig for a task:

var yeomanConfig = {
        [...]
        dev:      'false'
}

grunt.registerTask('server', function ()
{
        yeomanConfig.dev = true;
        [...]
}

but on reload I lose the yeomanConfig.dev override.
Is there a way to solve this?

the rules has a problem

/<\!DOCTYPE.+?>/i in the rules, what?
Sometimes, the rule can be a problem. Other rules is not enough?

Livereload shadow dom web components

I have a simple web component demo, with a single component containing html, css and js. I would like to reload the exact asset when it changes (NOT the entire page).

gulp.task('watch', function () {
    gulp.watch(['/**/*.css'], function (event) { console.log('css', event.path); gulp.src(event.path).pipe(connect.reload()); });
    gulp.watch(['/**/*.html'], function (event) { gulp.src(event.path).pipe(connect.reload()); });
    gulp.watch(['/**/*.js'], function (event) { gulp.src(event.path).pipe(connect.reload()); });
});

When I modify any html/js files they are updated automatically via livereload and it works! EVEN if the html or js is INSIDE the web component e.g.

<link href="header-custom.css" rel="stylesheet" />
<template>
    <p>Hello <strong></strong></p>
</template>
<script src="header-custom.js"></script>

However when updating css files inside the same webcomponent it does not livereload :( The event does fire correctly, so watch is detecting the file has changed, and the correct path:

css /web-components/src/components/header-custom/header-custom.css

I'm guessing the issue might be because the css is extracted from the web components and placed into the head of the document? This is how the page is rendered after a web component is loaded:

screen shot 2016-06-08 at 11 19 24 am

I believe it's a bug, or an unsupported feature, which just happens to work for html/js but not css!

Full source code is here:
https://github.com/kmturley/web-components

Demo:
http://kmturley.github.io/web-components/src/

Livereload is not work

I use grunt-connect-proxy module, then proxy to server.

The finally I get an error content-length .

I try to fix this problem.

res.writeHead = function() {

  var headers = arguments[arguments.length - 1]; 
  if (headers && typeof headers === 'object') {
    for (var name in headers) {
      if (/content-length/i.test(name)) {
        delete headers[name];
      }                                                                                                                                                                                                  
    }      
  } 

  var header = res.getHeader( 'content-length' );
  if ( header ) res.removeHeader( 'content-length' );

  writeHead.apply(res, arguments);
};  

The grunt-connect-proxy and connect-livereload modules will work fine.

Npm doesn't seem to be recognising 0.4.0 as the latest release

Not sure whether this is an npm registry issue or not, but i've been trying to install the latest gulp webapp generator, which depends on connect-livereload 0.4.0, and the install fails every time with npm not being able to find the latest release.

Is anyone else having similar issues? npm install connect-livereload finds and installs 0.3.2, while forcing an install of 0.4.0 or higher causes npm to report errors and fail.

npm http GET https://registry.npmjs.org/connect-livereload
npm http 200 https://registry.npmjs.org/connect-livereload
npm ERR! notarget No compatible version found: connect-livereload@'>=0.4.0-0 <0.5.0-0'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.0.2","0.0.3","0.1.0","0.1.1","0.1.2","0.1.3","0.1.4","0.2.0","0.3.0","0.3.1","0.3.2"]
npm ERR! notarget 
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

Snippet is not always included - overwritten res.write function fails to detect HTML if response is buffered

On line 110 the detection of whether this response is an HTML file assumes that the write function has received the entire response or contains a meaningful (i.e. uncut) chunk.

However, in many cases (specially on large files), the write function is called many times with parts of the response.

Therefore, if the chunks are broken in such way that the parts this middleware looks for are not whole, it will fail to acknowledge the response as HTML and thus not include the snippet.

This leads a finnicky behaviour with large files: the snippet is included only sometimes.

This seems to be related to #21, #20, #13 and #4.

The only alternative I can see is, unfortunately, to buffer the entire response before checking if it is HTML. Then, adding the snippet on the "end" function.

I will work on this issue on the coming weekend.

Doesn't inject snippet

It doesn't inject the snippet since res.send is always undefined.

We're going to use this in yeoman so I'd appreciate a quick resolution :)

parse error on HTML files over 65000 bytes

I've been trying to improve https://github.com/shakyshane/browser-sync using your techniques for injecting snippets...

I cloned this repo, increased the static.html file to exceed 65000 bytes & it causes your specs to fail...

I've personally found the only way to make this work for very large HTML docs is to remove the content-length header as proposed to me here BrowserSync/browser-sync#27 - although it doesn't seem ideal (and the author sent a follow-up PR with changes found here in connect-livereload).

Just wondering if you know about this limitation & whether you have any ideas for a fix?

Doesn't work on Windows

I ran the example and it doesn't work. Perhaps because I'm on Windows?

The task runs successfully but when I try to load localhost:3000, Chrome just sits there indefinitely.

I originally noticed this problem when working with generator-jekyllrb: robwierzbowski/generator-jekyllrb#6.

help/maintainer wanted

I personally don't use this module anymore and don't have time to maintain it. Is anyone interested in maintaining it? In my opinion It would need a "stream" based rewrite instead of "hacky" monkey patching essential response functions, but as I said I don't have the time for it.

Please let me know if you would be interested in maintaining or rewriting :-) it.

The server is up but no live reloading

Live reload is not working for me and I am using this sample taken from Cory House's Pluralsight course on React and Redux:

"use strict";

var gulp = require('gulp');
var connect = require('gulp-connect'); // Runs a local web server
var open = require('gulp-open'); // Open a URL in a web browser

var config = {
    port: 9005,
    devBaseUrl: 'http://localhost',
    paths: {
        html: './src/*.html',
        dist: './dist'
    }
}

// Start a local development server
gulp.task('connect', function() {
    connect.server({
        root: ['dist'],
        port: config.port,
        base: config.devBaseUrl,
        livereload: true,
        debug: true
    });
});

gulp.task('open', ['connect'], function() {
    gulp.src('dist/index.html')
        .pipe(open('', { url: config.devBaseUrl + ':' + config.port + '/' }));
});

gulp.task('html', function() {
    gulp.src(config.paths.html)
        .pipe(gulp.dest(config.paths.dist))
        .pipe(connect.reload());
});

gulp.task('watch', function() {
    gulp.watch(config.paths.html, ['html']);
});

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

livereload does not work with Angular2 component styleUrls

Hi, I have a problem with "livereload" when I use Angular 2, as you can see angular's component dynamically loads the CSS styles, the code below:

@component({
selector: 'ng2-app',
templateUrl: 'app/main.html',
styleUrls: ['app/main.css']
})

... it seems like 'livereload' script does not see these files.

Prepend snippet to the last </body>

Hello,

I've discovered a problem with the regex which searches a closing
body tag. The regex just matches the first not the last one.

Example (inside a script tag):

// Clear iframe
modalBody.contents().find('html').html('<head></head><body></body>');     

Becomes:

// Clear iframe
modalBody.contents().find('html').html('<head></head><body>
<script type="text/javascript">document.write('<script src="http://unidev243:8529/livereload.js?snipver=1" type="text/javascript"><\/script>')</script>
</body>');

No injection when using Pug

Hey!

I tried to use connect-livereload, but the code got not injected into my files while running the server. Not sure, but i think it is because i'm using the view engine "Pug".

My gulp code:

gulp.task('server', () => {
  const server = plugins.liveServer.new('./index.js');
  server.start();
  gulp.watch(['./public/**/*', './views/**/*', './index.js'], (file) => {
    server.notify.apply(server, [file]);
  });
});

My index.js

const express = require('express');
const app = module.exports = express();

app.use(require('connect-livereload')({
     port: 35729
}));

When i include the livereload.js from gulp-live-server into my .pug file the reload is working fine.

any suggestions how i could use connect-livereload with pug?

Enhancement Request: better if default livereload server port to be empty

The code below will add <script src="//myhost.com:443/livereload.js?snipver=1" async="" defer=""></script> to a html,

const app = express();
app.use(connect_livereload({
    port: 443,
}))

However, is most commonly cases, livereload is on the same server with the app, so using an empty port should be more convenient.

const app = express();
app.use(connect_livereload())
>> <script src="//myhost.com/livereload.js?snipver=1" async="" defer=""></script>

from: (index.js)

  var disableCompression = opt.disableCompression || false;
  var port = opt.port || 35729;
  var plugins = opt.plugins || [];

  function snippet(host) {
    var src = opt.src || '//' + host + ':' + port + '/livereload.js?snipver=1';
    return [src].concat(plugins).map(function(source) {
      return '<script src="' + source + '" async="" defer=""></script>';
    }).join('');
  }

to:

  var disableCompression = opt.disableCompression || false;
  var port = opt.port;
  var plugins = opt.plugins || [];

  function snippet(host) {
    var src = opt.src || '//' + host + (port ? ':' + port: '') + '/livereload.js?snipver=1';
    return [src].concat(plugins).map(function(source) {
      return '<script src="' + source + '" async="" defer=""></script>';
    }).join('');
  }

Is it possible to have snippet a part of option?

I know this is not a part of original goal, to use livereload.js.

However, I wanted to inject my own script using this. but, snippet is hard-coded and it's not a part of option, so I could not.

Only loads on second request

On first request it just loads forever. If i stop and refresh it loads immediately.

This does not happen when this middleware is not included.

SSL Support

At the moment it appears that the getSnippet() method implicitly injects the script via http. This means that the script is blocked as insecure content.

Would it be possible to include the script as protocol-less, or have an option to set the protocol.

Allow include option to complement ignore

I'm working on an app which allows the user to download files of many different types such as .doc and .pdf files. I can add each type to the ignore list but it is rather laborious.

I'd like to suggest an option to configure a list of file types to include rather than ignore. Only files that match these types would have the livereload script injected and all others would be ignored.

Thanks!

Not injecting when using EJS

I'm unable to get this middleware to work - I think it's because I'm using EJS. The file is accessible at the given port, but it's not being injected to the page at all.

My server.js:

const path = require('path');
const express = require('express');
const ejs = require('ejs');

const app = express();

/* Views */
app.set('views', path.join(__dirname, 'app/views'));

/* Static assets */
app.use(express.static(path.join(__dirname, 'app/static')));

/* Live reload */
if (app.get('env') === 'development') {
  app.use(require('connect-livereload')({
    port: 35729,
  }));
}

/* EJS */
app.engine('html', ejs.renderFile);
app.set('view engine', 'ejs');

/* Routes */
app.get('/', (req, res) => {
  res.render('pages/index');
});

/* Serve */
const PORT = process.env.PORT || 1212;
app.listen(PORT, () => {
  console.log(`App is listening to ${PORT}...`);
  console.log(`env: ${app.get('env')}`);
  console.log('Press Ctrl+C to quit.');
});

livereload.js is properly accessible at http://localhost:35729/livereload.js, so the issue has to be with the middleware. I've also made sure that the middleware was being loaded - adding a console.log('Using lr'); inside the if statement verifies this.

not working with jade or scss

i am using express, jade, scss and listening on port 9000
this is the error i get in my web console
GET http://localhost:35729/livereload.js?snipver=1 anonymous function

here is my app.js
var pagejs= '../routes';

var express = require('express')
, livereload = require('connect-livereload')
, home = require(pagejs)
, user = require(pagejs+'/user')
, http = require('http')
, path = require('path')
, events = require(pagejs+'/events')
, contact= require(pagejs+'/contact')
, abouttedx = require(pagejs+'/about')
, sponser = require(pagejs+'/sponsers');

var app = express();

function viewConfig(app){
app.set('views', __dirname + './../views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
//app.use(express.bodyParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, './../public')));
app.set('port', process.env.PORT || 9000);
}

app.configure('production', function(){
viewConfig(app);
});

app.configure('development', function(){
app.use(express.errorHandler());
app.use(livereload());
viewConfig(app);
});

app.get('/', home.index);
app.get('/talks', home.year);
app.get('/users', user.list);
app.get('/events', events.eventspage);
app.get('/about', abouttedx.aboutpage);
app.get('/sponser', sponser.sponserpage);
app.get('/contact', contact.contactuspage);

http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});

Using connect-livereload in an Express node app

I posted my question on S.O. here but will paste it below in case someone can resolve my issues:

Following this great article on how to use npm as a build tool, I would like to implement it when building a nodejs express web app.
My node app is created on port 8080, this is a simplified version of my server.js file:

var env = process.env.NODE_ENV

var path = require('path');
var express = require('express');
var logger = require('morgan');

var routes = require('./routes');

var app = express();

app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express)

var Oneday = 86400000;
app.use(express.static(__dirname + '/www', {
    maxAge: env == 'development' ? 0 : Oneday
}));

app.use(logger('dev'));

app.use(express.static(path.join(__dirname, '/public'), {
    maxAge: env == 'development' ? 0 : Oneday
}))

if (env == 'development') {
    // var liveReloadPort = 9091;
    app.use(require('connect-livereload')({
        port: 8080
        // src: "js/"
            // port: liveReloadPort
    }));
}

routes.blog(app);
routes.frontend(app, passport);

app.use(function(err, req, res, next) {
    console.log(err.stack);
    res.status(500).send({
        message: err.message
    })
});

app.listen(app.get('port'));
console.log('Server starting on port: ' + app.get('port'));

The file that I'm watching before needing to reload is in www/js.
I am using npm as a build tool and before launching server.js with npm I launch a separate process that does watchify source/js/app.js -v -o wwww/js/bundle.js
I did checked that watchify works correctly, updating as I save my files. But there is no livereload once a file is changed.
The error I get in the console is:
Uncaught SyntaxError: Unexpected token <
and I can see that connect-livereload inserted this script in the html:

<script>
//<![CDATA[
document.write('<script src="//' + (location.hostname || 'localhost') + ':8080/livereload.js?snipver=1"><\/script>')
//]]>
</script>
<script src="//localhost:8080/livereload.js?snipver=1"> </script>

I tried also to use live-reload as mentionned in the original article but without success and I am not sure it's the right plugin to use as live-reload launches a server, when I already start one with express.
Any ideas?

Livereload.js is inserted to wrong place

If JavaScript has </body> as string like this

<script>
var s = '</body>'
</script>
</body>
</html>

livereload.js is inserted to first match of </body>

<script>
    var s = '
<script type="text/javascript">document.write('<script src="' + (location.protocol || 'http:') + '//' + (location.hostname || 'localhost') + ':35729/livereload.js?snipver=1" type="text/javascript"><\/script>')</script>
</body>';
</script>
</body>
</html>

Livereload snippet doesn't work on Windows

So this project is now mentioned in the readme for grunt-contrib-watch as a way of getting a livereload snippet to use as connect middleware to use with watch's new livereload functionality.

The only issue with that is the snippet doesn't work on Windows. Please see this issue: yeoman/generator-webapp#63

Meanwhile, the grunt-contrib-livereload livereload snippet works perfectly for me.

I'll try to investigate when I have some time, but it's low on my priority list.

<pre> trap for snippet

For some reason live reload script snippet is appearing inside <pre> element if you have &lt; plus \n there and don’t have optional <body> element. I would expect it to appear right after <p>bar</p> instead. This document is completely valid:

<!DOCTYPE html>
<title>Title</title>
<p>foo</p>
<pre>&lt;
</pre>
<p>bar</p>

It wouldn’t be a problem if it wasn’t <pre> element: I’m getting an extra line inside it because of misplaced snippet.

screen shot 2014-09-21 at 18 04 49

I’m using v0.4.0 as part of grunt-contrib-connect v0.8.0.

livereload.js load error for proxy cases.

if use proxy like ngrok, the livereload.js will load from location.hostname, but it not exist. for example, i use ngrok map http://localhost:7001 to https://009c4b13.ngrok.io/, but connect-livereload will use the hostname as where the livereload.js serves "https://009c4b13.ngrok.io/:35729", actually it should be load from "http://localhost:35729". if the default hostname shoud be removed:

change:
var src = opt.src || "//' + (location.hostname || '" + hostname + "') + ':" + port + "/livereload.js?snipver=1";
to
var src = opt.src || "//' + ('" + hostname + "') + ':" + port + "/livereload.js?snipver=1";

Overwriting writeHead function

Hey

Today I spent some time trying to figure out why snippets of the code with writeHead function does not work correctly with my connect based application

After digging in the code I found out that livereload overwrites writeHead function in httpResponse of node. (line 124 in index.js).

Is it done on purpose? If so what is the rationale behind this? I am just wondering if this is done on purpose what will happen if I overwrite manually response code and add some headers with the setHeader function

Didn't work with document with implicit </body>

This is a "valid" html 5 document.

<!doctype html>
<title></title>

But since there is no specified body in this case, this script is not working.
Previously I made this PR but you have one more test now bodyExists(). How can we handle that use case ? Maybe we can check if there is a doctype, to see if we have a html doc, & eventually try to append script before or or just append at the end ?

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.