intesso / connect-livereload Goto Github PK
View Code? Open in Web Editor NEWconnect middleware for adding the livereload script to the response
License: MIT License
connect middleware for adding the livereload script to the response
License: MIT License
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
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?
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.
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?
For security reasons we are disallowing inline styles and scripts.
http://www.html5rocks.com/en/tutorials/security/content-security-policy/
As we are using the same security settings in our development environments we are running into issues when using connect-livereload as it relies on inline scripts.
Any ideas how we could handle this?
Need tests.
I've got everything working on the root URL like http://localhost:8000
but I'm also using connect-modrewrite to enable pushState URLs and reloading doesn't work on any of those subpaths. When the page reloads you'll just see Cannot GET /<url>
.
Relevant files: https://gist.github.com/swalkinshaw/8890919e3a8a72b4b495
I've tried to vary the order of the middleware's but other orders just break it further.
/<\!DOCTYPE.+?>/i
in the rules, what?
Sometimes, the rule can be a problem. Other rules is not enough?
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:
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
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.
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.
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.
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 :)
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?
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.
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.
Are there any possibilities to inject the script for requests with not Accept: html
header? In other words to disable this check?
And what is the exact rationale behind the accept
function?
It appears the version number in the package.json hasn't been updated with pull requests.
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']);
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.
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>');
Please see expressjs/cookie-session#14
Thanks!
package.json has version 0.5.4, but npm shows 0.5.3 as the latest release: https://www.npmjs.com/package/connect-livereload
Will 0.5.4 be tagged as a release, or is it not yet stable? Thanks!
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?
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('');
}
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.
I think it might be related to: gruntjs/grunt-contrib-connect#65
I'm getting this error when I connect with the mmiddleware:
Failed to load resource http://localhost:35729/livereload.js?snipver=1
Any idea why is not loading?
Thanks
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.
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.
//how about using it with middleware in koa2 or express?
I am missing a gulp recipe with nodemon
and express
altogether. The plugin https://www.npmjs.org/package/gulp-connect does not indicate a solution. Thanks for your help!
After grunt-contrib-htmlmin
handle the html file, there not close tag </body></html>
, and just one line, so onnect-livereload
could not inject the snippet.
I'm using grunt-contrib-connect
and when I have an html file that is bigger than 40kb, the livereload snippet is not being inserted.
Here's the issue on the grunt-contrib-connect side: gruntjs/grunt-contrib-connect#20 (comment)
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!
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.
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'));
});
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?
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>
Using https://www.npmjs.com/package/superstatic doesn't seem to inject the LR script.
var app = connect()
.use(require('connect-livereload')())
.use(superstatic({ ... }))
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.
For some reason live reload script snippet is appearing inside <pre>
element if you have <
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><
</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.
I’m using v0.4.0 as part of grunt-contrib-connect v0.8.0.
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";
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
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 ?
2.0 was failing intermittently for me until I disabled the Chrome LiveReload extension. If others can confirm I'll add a brief note to the readme.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.