patrick-steele-idem / browser-refresh Goto Github PK
View Code? Open in Web Editor NEWNode.js module to enable server restart and browser refresh in response to file modifications
Node.js module to enable server restart and browser refresh in response to file modifications
Hi guys,
Thanks for all your great work! I'm really excited trying to get this browser refresh to work.
My marko hot reload works perfectly, so this is my last step for true mastery :)
Here is my main .marko index page with <browser-refresh enabled="true" />
at the end of body.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="semantic.min.css">
<script src="semantic/dist/semantic.min.js"></script>
<title>Article Title</title>
</head>
<body>
<h1>My Article here and there! BLIP BLAP SWIP SNAP</h1>
<h2>HELLO MIKE</h2>
<browser-refresh enabled="true" />
</body>
</html>
And my server config:
start: function(appContainer) {
let port = options.port || this.default.port;
let refresh = options.refresh || this.default.refresh;
let reload = appContainer.reload || options.reload || this.default.reload;
if (refresh) {
require('marko/browser-refresh').enable();
console.log('Marko browser refresh enabled!!');
console.log('Install browser-refresh');
console.log('npm install browser-refresh-taglib --save');
console.log('npm install browser-refresh --global');
console.log('Start server with: $ browser-refresh server.js');
console.log('Add <browser-refresh enabled="true" /> to just before </body> in your main page template');
}
if (reload) {
// configure marko hot reload :) works!!!
let markoConfig = require('./markoConfig');
markoConfig({views: appContainer.views});
}
app.listen(port, function() {
console.log(`Marko appplication ready on port ${port}`);
// for browser refresh!
if (process.send) {
process.send('online');
}
});
This is what I get when I start my server using browser-refresh
11:01 $ browser-refresh test
[browser-refresh] Watching: /Users/kristianmandrup/repos/markoa/markoa-tester
[browser-refresh] Ignore rule: **/node_modules
[browser-refresh] Ignore rule: **/node_modules/**
...
[browser-refresh] Ignore rule: dist
[browser-refresh] App started (pid: 47276)
Missing static: in options for static mw
Added static dir:public
Added static dir:dist
Added static dir:semantic/dist
Marko browser refresh enabled!!
Install browser-refresh
npm install browser-refresh-taglib --save
npm install browser-refresh --global
Start server with: $ browser-refresh server.js
Add <browser-refresh enabled="true" /> to just before </body> in your main page template
Watching: .marko templates in /Users/kristianmandrup/repos/markoa/markoa-tester/apps for hot reload!!
Marko appplication ready on port 4005
[browser-refresh] Server is ready. Watching files for changes.
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
[browser-refresh] File has been changed: apps/index/page/index.marko.js
[browser-refresh] Restarting app...
[browser-refresh] App started (pid: 47279)
[browser-refresh] File has been changed: apps/index/page/index.marko.js
[browser-refresh] Restarting app...
[browser-refresh] App started (pid: 47280)
...
[browser-refresh] Waited 1500ms without receiving "online" from child process. Page refresh triggered over WebSockets connection.
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
Timed out :(
The browser is not automatically started on the index page at localhost:4005
(should it?).
If I try to go there directly, it simply reverts to the previous page. It can't seem to load the real server, doing some kind of back history jump instead. Any ideas?
I expect it would work similar to BrowserSync but I was unable to make that work as well... might try again now that marko hot reload works however... :P
But I'd rather get your awesome browser refresh solution working. I know I'm SO close, just one obvious thing I'm missing or misunderstanding I'm sure :)
Thanks as always guys :)
Cheers!!! Kristian
PS: I created a jade-marko Gulp transformer for you ;)
I can't get the client to work correctly, window.io seems to be undefined. I get the message
Uncaught TypeError: Cannot read property 'connect' of undefined
Is there a missing dependency (socket.io)?
In line with the following issue:
patrick-steele-idem/ignoring-watcher#3
Some environments in OS X do not correctly use fsevents to watch files. Possibly add the ability to pass an additional configuration variable within .browser_refresh to override the chokidar usePolling in those instances?
.browser-refresh-ignore does not seem to honor overrides. For example
!/node_modules/my-module
... does not currently work.
Note: I'm not sure if having the "my-module" as a symbolic link matters or not, but my module is a symbolic link.
Can I use browser-refresh and write ES6 code?
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at process.addListener (events.js:160:15)
at process.on.process.addListener (node.js:796:26)
at Launcher.fork (/Users/psteeleidem/development/github/patrick-steele-idem/browser-refresh/lib/Launcher.js:67:17)
at Launcher.<anonymous> (/Users/psteeleidem/development/github/patrick-steele-idem/browser-refresh/lib/Launcher.js:94:22)
at ChildProcess.g (events.js:180:16)
at ChildProcess.emit (events.js:117:20)
at Process.ChildProcess._handle.onexit (child_process.js:820:12)
Hello, I was just wondering if there is some way of manually specifying the port browser-refresh uses to expose the client-side script?
NSP reports a potential vulnerability in dependency fresh
: https://nodesecurity.io/advisories/526
Does it make sense to upgrade an express
to version ^4.15.5
?
I get in the console:
localhost/:18 GET http://localhost:5000/%7Bprocess.env.BROWSER_REFRESH_URL%7D 404 (Not Found)
It seems that the curly braces are interpreted the wrong way. Page is not refreshed, but in Terminal I get:
[browser-refresh] Server is ready. Page refresh triggered over WebSockets connection.
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
What can I do?
I am trying to install browser refresh globally using:
sudo npm install -g browser-refresh
I keep seeing the below error
LM-SJC-11000532:~ jigmehta$ sudo npm install -g browser-refresh
[email protected] install /usr/local/lib/node_modules/browser-refresh/node_modules/ignoring-watcher/node_modules/chokidar/node_modules/fsevents
node-gyp rebuild
CXX(target) Release/obj.target/fse/fsevents.o
In file included from ../fsevents.cc:6:
../node_modules/nan/nan.h:339:13: error: no member named 'New' in 'v8::String'
return _NAN_ERROR(v8::Exception::Error, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
~~~~~~~~~~~~^
../node_modules/nan/nan.h:343:5: error: no member named 'ThrowException' in namespace 'v8'
_NAN_THROW_ERROR(v8::Exception::Error, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:11: note: expanded from macro '_NAN_THROW_ERROR'
v8::ThrowException(_NAN_ERROR(fun, errmsg));
~~~~^
../node_modules/nan/nan.h:343:5: error: no member named 'New' in 'v8::String'
_NAN_THROW_ERROR(v8::Exception::Error, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:26: note: expanded from macro '_NAN_THROW_ERROR'
v8::ThrowException(_NAN_ERROR(fun, errmsg));
^~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
~~~~~~~~~~~~^
../node_modules/nan/nan.h:348:9: error: no type named 'ThrowException' in namespace 'v8'
v8::ThrowException(error);
~~~~^
../node_modules/nan/nan.h:355:65: error: no member named 'New' in 'v8::String'
v8::Localv8::Value err = v8::Exception::Error(v8::String::New(msg));
~~~~~~~~~~~~^
../node_modules/nan/nan.h:357:26: error: no member named 'New' in 'v8::String'
obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber));
~~~~~~~~~~~~^
../node_modules/nan/nan.h:357:65: error: too few arguments to function call, expected 2, have 1
obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber));
~~~~~~~~~~~~~~ ^
/Users/jigmehta/.node-gyp/0.12.7/deps/v8/include/v8.h:2012:3: note: 'New' declared here
static Local New(Isolate* isolate, int32_t value);
^
In file included from ../fsevents.cc:6:
../node_modules/nan/nan.h:369:12: error: no member named 'New' in 'v8::String'
return _NAN_ERROR(v8::Exception::TypeError, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
~~~~~~~~~~~~^
../node_modules/nan/nan.h:373:5: error: no member named 'ThrowException' in namespace 'v8'
_NAN_THROW_ERROR(v8::Exception::TypeError, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:11: note: expanded from macro '_NAN_THROW_ERROR'
v8::ThrowException(_NAN_ERROR(fun, errmsg));
~~~~^
../node_modules/nan/nan.h:373:5: error: no member named 'New' in 'v8::String'
_NAN_THROW_ERROR(v8::Exception::TypeError, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:26: note: expanded from macro '_NAN_THROW_ERROR'
v8::ThrowException(_NAN_ERROR(fun, errmsg));
^~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
~~~~~~~~~~~~^
../node_modules/nan/nan.h:377:12: error: no member named 'New' in 'v8::String'
return _NAN_ERROR(v8::Exception::RangeError, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
~~~~~~~~~~~~^
../node_modules/nan/nan.h:381:5: error: no member named 'ThrowException' in namespace 'v8'
_NAN_THROW_ERROR(v8::Exception::RangeError, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:11: note: expanded from macro '_NAN_THROW_ERROR'
v8::ThrowException(_NAN_ERROR(fun, errmsg));
~~~~^
../node_modules/nan/nan.h:381:5: error: no member named 'New' in 'v8::String'
_NAN_THROW_ERROR(v8::Exception::RangeError, errmsg);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:26: note: expanded from macro '_NAN_THROW_ERROR'
v8::ThrowException(_NAN_ERROR(fun, errmsg));
^~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
~~~~~~~~~~~~^
../node_modules/nan/nan.h:727:49: error: too few arguments to function call, single argument 'isolate' was not specified
v8::Localv8::Object obj = v8::Object::New();
~~~~~~~~~~~~~~~ ^
/Users/jigmehta/.node-gyp/0.12.7/deps/v8/include/v8.h:2388:3: note: 'New' declared here
static Local New(Isolate* isolate);
^
In file included from ../fsevents.cc:6:
../node_modules/nan/nan.h:733:49: error: too few arguments to function call, single argument 'isolate' was not specified
v8::Localv8::Object obj = v8::Object::New();
~~~~~~~~~~~~~~~ ^
/Users/jigmehta/.node-gyp/0.12.7/deps/v8/include/v8.h:2388:3: note: 'New' declared here
static Local New(Isolate* isolate);
^
In file included from ../fsevents.cc:6:
../node_modules/nan/nan.h:740:12: error: no member named 'Dispose' in 'v8::Persistent<v8::Object, v8::NonCopyablePersistentTraitsv8::Object >'
handle.Dispose();
~~~~~~ ^
../node_modules/nan/nan.h:741:12: error: no member named 'Clear' in 'v8::Persistent<v8::Object, v8::NonCopyablePersistentTraitsv8::Object >'
handle.Clear();
~~~~~~ ^
../node_modules/nan/nan.h:746:39: error: no member named 'NewSymbol' in 'v8::String'; did you mean 'IsSymbol'?
NanPersistentToLocal(handle)->Set(NanSymbol("callback"), fn);
^~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:181:38: note: expanded from macro 'NanSymbol'
~~~~~~~~~~~~^
/Users/jigmehta/.node-gyp/0.12.7/deps/v8/include/v8.h:1379:8: note: 'IsSymbol' declared here
bool IsSymbol() const;
^
In file included from ../fsevents.cc:6:
../node_modules/nan/nan.h:746:39: error: call to non-static member function without an object argument
NanPersistentToLocal(handle)->Set(NanSymbol("callback"), fn);
^~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:181:38: note: expanded from macro 'NanSymbol'
~~~~~~~~~~~~^~~~~~~~~
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/fse/fsevents.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: make
failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:269:23)
gyp ERR! stack at ChildProcess.emit (events.js:110:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1074:12)
gyp ERR! System Darwin 14.4.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/browser-refresh/node_modules/ignoring-watcher/node_modules/chokidar/node_modules/fsevents
gyp ERR! node -v v0.12.7
gyp ERR! node-gyp -v v2.0.1
gyp ERR! not ok
npm WARN optional dep failed, continuing [email protected]
[email protected] install /usr/local/lib/node_modules/browser-refresh/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/utf-8-validate
node-gyp rebuild
CXX(target) Release/obj.target/validation/src/validation.o
SOLINK_MODULE(target) Release/validation.node
[email protected] install /usr/local/lib/node_modules/browser-refresh/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/bufferutil
node-gyp rebuild
CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
SOLINK_MODULE(target) Release/bufferutil.node
[email protected] install /usr/local/lib/node_modules/browser-refresh/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/node_modules/bufferutil
node-gyp rebuild
CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
SOLINK_MODULE(target) Release/bufferutil.node
[email protected] install /usr/local/lib/node_modules/browser-refresh/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/node_modules/utf-8-validate
node-gyp rebuild
CXX(target) Release/obj.target/validation/src/validation.o
SOLINK_MODULE(target) Release/validation.node
/usr/local/bin/browser-refresh -> /usr/local/lib/node_modules/browser-refresh/bin/browser-refresh
[email protected] /usr/local/lib/node_modules/browser-refresh
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
hi, my client browser-refresh not work. How put the code ? Please update your readme (he is false and not updated)
The default ignore options doesn't ignore changes in the .git
directory
[browser-refresh] Server is ready. Page refresh triggered over WebSockets connection.
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
[browser-refresh] File has been changed: .git/FETCH_HEAD
[browser-refresh] Restarting app...
[browser-refresh] App started (pid: 23543)
Server started! Try it out:
Not using Marko or Dust?
When browser-refresh launches your app a new BROWSER_REFRESH_URL environment variable is added with the URL that should be used to include the client-side script. The value of BROWSER_REFRESH_URL will be similar to http://localhost:12345/browser-refresh.js (the port is random). You should include this library using code similar to the following:
'<script src="{BROWSER_REFRESH_URL}"></script>'
why I can not get the 'BROWSER_REFRESH_URL'
This is just a heads up to let you know that I have just released a Drupal module to easily integrate browser-refresh with this popular CMS so that developers have a very easy way to utilise your great node module. You can fine it at https://www.drupal.org/project/browser_refresh and I'd be happy if you wanted to mention it in your README here on GitHub.
I'll also publish a blog post shortly, anything you want me to mention there?
I get the following error in the client side console:
2127.0.0.1/:25 GET http://127.0.0.1:4000/%7Bprocess.env.BROWSER_REFRESH_URL%7D net::ERR_ABORTED 404 (Not Found)
client/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="static/style.css">
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="chart" width="400" height="400"></canvas>
<script src="static/client.js"></script>
<script src="{process.env.BROWSER_REFRESH_URL}"></script>
</body>
</html>
server.js:
const express = require('express');
const app = express();
const port = 4000;
app.use('/static', express.static(__dirname + '/client'));
app.get('/', function (req, res) {
res.sendfile('client/index.html');
})
app.listen(port, () => {
console.log(`Listening on port ${port}`);
if (process.send) {
process.send('online');
}
});
As you can see, I don't have a templating engine. I think you should make it clear that it only supports using with templating and not with static html files.
Perhaps you could manually allocate the port which browser refresh uses, then just hardcode it in?
So you set a port field in the process.send, which then sets the browser-refresh server up which serves the browser-refresh.js file, then as I stated before, just hardcode <script src="http://127.0.0.1:4001/browser-refresh.js"></script>
in the html file. This should make it work for static html files.
I have browser-refresh
running. Whenever I tab to SourceTree (viewing commit history), it seems to trigger a file refresh for any file in that diff. Additionally, clicking around to view different parts of the commit history will trigger refreshes similarly. I'm not sure if this is a bug with SourceTree (what are they doing to the files?), but I can see that watcher.on('modified')
is emitting a change
event for each file.
I understand that Browser-refresh exec replace the command line and defer to node.
Is it possible to use iojs instead without having to rename it to node ?
a config where I can set the exec name.
Thank you.
I am not able to get debugging working with browser-refresh. In comparison, these steps work with nodemon:
terminal1: nodemon --debug server.js
terminal2: node-inspector (provides a URL and I'm off an running and debugging breaks trigger)
With browser-refresh I've tried:
terminal1: browser-refresh server.js --debug
terminal2: node-inspector (gives a URL but break points don't seem to do anything and it behaves differently).
Thanks for any help!
Hey,
Would be cool to allow the user to type rs
in the console which would manually restart the server. Sometimes I change things in other folder and I would like to restart the server. Pressing ctrl + c
and then typing npm run dev
which starts both my node and webpack server takes to much time. Having an rs
command would only restart my node server (not webpack since its running in the background) and would save a bunch of time. Nodemon already does this.
Thanks.
Same as title.
I plan on only using this in a development environment. Can this package be installed via npm as a dependency or devdependency without breaking or loosing any of its features? If not, "why" does this need to be installed as a global?
It would be nice if open
was used to automatically open the browser to a url when browserrefresh
starts/restarts an app.
This could be configured like so:
process.send({ event:'online', url:'http://localhost:8080' });
And it would open the browser if there weren't any websocket connections active.
I am running browser-refresh in Gitpod. As a result, it's served over the internet by https not http.
When I try to load the browser-refresh.js script, using the BROWSER_REFRESH_URL it does not work because I am not on localhost and so I get a connection refused.
Gitpod creates a URL that combines a port and a base URL. So with my app served on port 3000, the URL is:
https://3000-fa269f1c-2cab-483e-a100-c003b021d84c.ws-us0.gitpod.io/
The random port assignment for this run is: 41597 so when I synthesized the port that would be the equivalent, I can read the js file at:
https://41597-fa269f1c-2cab-483e-a100-c003b021d84c.ws-us0.gitpod.io/browser-refresh.js
When I plug that in as the source URL (either http or https) I get a message that it's mixed content. I turned off the mixed content error in Chrome but still get a warning and no reloading.
It may be that the architecture does not permit this solution, but it there's a way, I'm willing to help
Here is a gitpod workspace snapshot:
https://gitpod.io#snapshot/e50bc0b6-fa4e-4eec-a9be-6b485f29dd33
It will probably come up with a different websocket port so you would have to open the port (tab next to the console tab)
> NODE_PATH="$(pwd)" NODE_ENV=development ./node_modules/.bin/browser-refresh --inspect ./application/index.js
[browser-refresh] Watching: /Users/km/dev/pcap-reader/web
[browser-refresh] Ignore rule: node_modules/
[browser-refresh] Ignore rule: static/
[browser-refresh] Ignore rule: .cache/
[browser-refresh] Ignore rule: .*
[browser-refresh] Ignore rule: *.marko.js
[browser-refresh] Ignore rule: *.dust.js
[browser-refresh] Ignore rule: *.coffee.js
[browser-refresh] App started (pid: 28070)
Debugger listening on ws://127.0.0.1:9229/26b8489b-3d11-4697-a8fa-360a9e892eae
For help see https://nodejs.org/en/docs/inspector
Application starting
Application listening to port: 8080
process online sent
[browser-refresh] Server is ready. Watching files for changes.
[browser-refresh] File has been changed: application/frontend/components/smart/counter/counter.marko
[browser-refresh] Special reload: /application/frontend/components/smart/counter/counter.marko
[lasso] File modified: /Users/km/dev/pcap-reader/web/application/frontend/components/smart/counter/counter.marko
[lasso/browser-refresh] File modified: /Users/km/dev/pcap-reader/web/application/frontend/components/smart/counter/counter.marko
[marko/hot-reload] File modified: /Users/km/dev/pcap-reader/web/application/frontend/components/smart/counter/counter.marko
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
[marko/hot-reload] Template successfully reloaded: /Users/km/dev/pcap-reader/web/application/frontend/components/smart/counter/counter.marko.js
I don't see what I'm doing wrong.
index.html:
<!doctype html>
<html>
<head>
<title>webz</title>
<!-- CSS will be inserted here -->
<lasso-head/>
</head>
<body>
<!-- Top-level UI component: -->
<app/>
<!-- JS will be inserted here -->
<lasso-body/>
<!-- Used for the browser-refresh library -->
<browser-refresh/>
</body>
</html>
server.js:
console.log('Application starting');
const Koa = require('koa');
const Router = require('koa-router');
// Used for special reloading
require('lasso/browser-refresh').enable('*.marko *.css *.less *.styl *.scss *.sass *.png *.jpeg *.jpg *.gif *.webp *.svg');
// lasso configuration
require('lasso').configure({
plugins: [
'lasso-marko',
'lasso-sass',
],
});
const application = new Koa();
const router = new Router();
const template = require('marko').load(require.resolve('./frontend/components/smart/counter/counter.marko'));
router.get('/', (ctx, next) => {
ctx.type = 'html';
ctx.body = template.stream({});
});
application
.use(router.routes())
.use(router.allowedMethods());
const httpPortNumber = 8080;
// Start the server and listen to the specific port
application.listen(httpPortNumber, (error) => {
if (error) {
console.error(error);
process.exit(1);
}
console.log(`Application listening to port: ${httpPortNumber}`);
// Just in development mode
if (process.env.NODE_ENV === 'development') {
// For browser-refresh
if (process.send) {
process.send('online');
console.log('process online sent');
}
}
});
package.json:
{
"name": "web",
"description": "Web",
"version": "0.0.0",
"private": true,
"scripts": {
"test": "NODE_PATH=\"$(pwd)\" NODE_ENV=test ./node_modules/.bin/nyc --reporter=html --reporter=text ./node_modules/.bin/mocha ./test/ --exit",
"prod": "NODE_PATH=\"$(pwd)\" NODE_ENV=production node ./application/index.js",
"dev": "NODE_PATH=\"$(pwd)\" NODE_ENV=development ./node_modules/.bin/browser-refresh --inspect ./application/index.js",
"count": "./node_modules/.bin/cloc . --exclude-list-file=./.clocignore",
"lint": "./node_modules/.bin/eslint .",
"report": "./node_modules/.bin/nyc report"
},
"author": "Karl Morrison",
"license": "ISC",
"dependencies": {
"@lasso/marko-taglib": "^1.0.12",
"browser-refresh-taglib": "^1.1.0",
"koa": "^2.6.1",
"koa-router": "^7.4.0",
"lasso": "^3.2.6",
"lasso-marko": "^2.4.6",
"lasso-sass": "^3.0.0",
"marko": "^4.13.8",
"node-sass": "^4.9.4",
"socket.io": "^2.1.1",
"socket.io-client": "^2.1.1"
},
"devDependencies": {
"browser-refresh": "^1.7.3",
"cloc": "^2.3.4",
"eslint": "^5.7.0",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-plugin-import": "^2.14.0",
"mocha": "^5.2.0",
"nyc": "^13.1.0",
"selenium-standalone": "^6.15.3",
"webdriverio": "^4.14.0",
"webpack-cli": "^3.1.2"
}
}
warning marko-starter > browser-refresh > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
When installing npm i browser-refresh
I get the following warning:
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
Granted, a DoS is not a big deal since browser-refresh
is not something that will ever be used in a production environment, just thought I'd share my findings:
└─┬ [email protected]
└─┬ [email protected] (current version)
└─┬ [email protected] (latest release is 14.4.0 and uses glob 7.1.0)
└─┬ [email protected] (the 7.1.0 release uses minimatch 3.0.2)
└── [email protected]
Since .marko templates uses hot reloading, the server doesn't restart when editing .marko files.
The special case is when the app crash because of an error inside the template file. When you fix the template, hot reload loads the new .marko template but the app doesn't restart.
Would be nice to know when the app crashed, and if browser-refresh triggers a hot-reload because of a template saving, using that state to also restart the app as an edit on a .js file would do.
I just got this when updating my browser-refresh
packages.
warning browser-refresh > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
https://github.com/patrick-steele-idem/browser-refresh/blob/master/lib/client/refresher.js
I would suggest to implement the client JS refresher, this could help the user to call this function in browser-refresh-client
after filtering out the client/*.js
, so that the users could enjoy the fast changes for their client JS without refreshing the page. ;)
Any idea for my suggestion?
Hey,
It would be cool to have a quiet
option somehow that stops the console.logs from showing. Right now its printing wayyyyy too much.
Hi! I discover that when restarting server by made changes in js or another files which requires server restart then try to make changes in marko hot reloading it change marko files multiple times
for example after 4 times restarting server by changes in js and 1 time in marko file it output console this
[browser-refresh] Refresh triggered
[browser-refresh] File has been changed: admin/components/test/index.marko
[browser-refresh] Special reload: /admin/components/test/index.marko
[marko/hot-reload] File modified: /Users/elix/Documents/Projeler/NodeJs/marko-4/admin/components/test/index.marko
[marko/hot-reload] File modified: /Users/elix/Documents/Projeler/NodeJs/marko-4/admin/components/test/index.marko
[marko/hot-reload] File modified: /Users/elix/Documents/Projeler/NodeJs/marko-4/admin/components/test/index.marko
[marko/hot-reload] File modified: /Users/elix/Documents/Projeler/NodeJs/marko-4/admin/components/test/index.marko
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
My config file is
const refresh = require('browser-refresh-client');
const path = require('path');
module.exports.enable = () => {
var hotReload = require('marko/hot-reload');
hotReload.enable();
refresh
.enableSpecialReload('/{admin/assets/**,themes/*/assets/**,plugins/*/assets/**}', {
autoRefresh: false
})
.onFileModified(function(filePath) {
switch (path.extname(filePath)) {
case '.less' || '.styl' || '.scss' || '.sass' || '.css':
refresh.refreshStyles();
break;
case '.png' || '.jpg' || '.jpeg' || '.gif' || '.webp' || '.svg':
refresh.refreshImages();
break;
case '.js':
refresh.refreshPage();
break;
default:
refresh.refreshPage();
}
});
}
i think it's bind chokidar on marko files everytime when server restarts
Hello, I'm using Marko.js, Lasso.js and npm library load-google-maps-api. I'm doing a test app with just one page.
import loadGoogleMapsApi from 'load-google-maps-api'
class {
onMount() {
// Google Maps API Stuff
}
}
lasso-page package-path="./browser.json"
<!DOCTYPE html>
html
head
title -- App
lasso-head
body
div.search-container.location-search
div.input-field
p.input-label -- Search
input#pac-input.controls type="text" placeholder="Search Box"
div#map
lasso-body
browser-refresh
When I access this page using broswer-refresh server.js
everything works fine. I can see the map on screen, search for places and add markers. But when I run node server.js
it doesn't work anymore, I can't see the map and a simple log in the onMount()
method is not shown in the console. Instead, I get this error message: Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': Nodes of type '#text' may not be inserted inside nodes of type '#document'.
Thank you.
Explicitly set usePolling
to false
seems to solve the problem even though usePolling
defaults to false
.
This error pops up every time causing the server to restart on every refresh, but it still functions as expected. I'm thinking that a simple catch and ignore would solve this.
$ ./node_modules/browser-refresh/bin/browser-refresh
[browser-refresh] Watching: /Users/williamrusnack/Documents/make_faster
[browser-refresh] Ignore rule: *.DS_Store
[browser-refresh] Ignore rule: public/stylesheets/dst/*
[browser-refresh] App started (pid: 25827)
module.js:473
throw err;
^
Error: Cannot find module '/Users/williamrusnack/Documents/make_faster/index.js'
at Function.Module._resolveFilename (module.js:527:15)
at Function.Module._load (module.js:453:25)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:201:16)
at bootstrap_node.js:626:3
App stopped unexpectedly
[browser-refresh] Waited 1500ms without receiving "online" from child process. Page refresh triggered over WebSockets connection.
[browser-refresh] Triggering refresh of client pages...
[browser-refresh] Refresh triggered
"dev": "browser-refresh --require ts-node/register ./src/index.ts"
This is the command im using to run my servers backend.
"__dev": "cross-env nodemon --ext 'ts' --watch 'src' --exec 'cross-env NODE_ENV=development PORT=8080 ts-node --files ./src/index.ts'",
This is the old dev command I was using before trying browser-refresh
When running browser-refresh, i get typing errors, even though it was working perfectly before I used browser-refresh
/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:513
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/index.ts:114:40 - error TS2339: Property 'realIp' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
114 if (ipffffSplit !== undefined) req.realIp = ipffffSplit; else req.realIp = ip;
~~~~~~
src/index.ts:114:71 - error TS2339: Property 'realIp' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
114 if (ipffffSplit !== undefined) req.realIp = ipffffSplit; else req.realIp = ip;
~~~~~~
at createTSError (/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:513:12)
at reportTSError (/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:517:19)
at getOutput (/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:752:36)
at Object.compile (/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:968:32)
at Module.m._compile (/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:1056:42)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .ts] (/media/chen/storage/development/urlshortener/backend/node_modules/ts-node/src/index.ts:1059:12)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
App stopped unexpectedly
This is my tsconfig.json
{
"compilerOptions": {
"allowJs": false,
"allowSyntheticDefaultImports": true,
"alwaysStrict": true,
"baseUrl": "./src",
"checkJs": false,
"declaration": false,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"importsNotUsedAsValues": "error",
"incremental": true,
"lib": ["es2020"],
"module": "commonjs",
"moduleResolution": "node",
"noEmit": false,
"noEmitOnError": true,
"noImplicitAny": true,
"noImplicitReturns": false,
"noImplicitThis": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
// "outDir": "./dist",
"pretty": false,
"removeComments": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": false,
"strict": true,
"strictBindCallApply": true,
"strictNullChecks": false,
"suppressImplicitAnyIndexErrors": true,
"inlineSourceMap": true,
"target": "es2020",
"typeRoots": ["./src/typings", "./node_modules/@types"],
},
"exclude": ["node_modules"],
"include": ["./src/**/*"]
}
What's the problem here?
Need elegant way to pass node.js runtime arguments like harmony flag
I am looking to start a debug session along with browser-refresh, is it possible?
NODE_ENV=production browser-refresh app.js -r babel-register -r babel-polyfill
/home/karl/dev/sketch/experiment/socketio/app.js:12
import cluster from 'cluster';
^^^^^^
SyntaxError: Unexpected token import
NODE_ENV=production browser-refresh -r babel-register -r babel-polyfill app.js
module.js:442
throw err;
^
Error: Cannot find module '/home/karl/dev/sketch/experiment/socketio/-r'
I'm guessing I can't pass these arguments? Under https://github.com/patrick-steele-idem/browser-refresh#usage states that I should be able to pass them, apparently not? Any ideas?
Can I use browser-refresh and write Coffee Script code?
This is a great module and I've integrated that with Drupal successfully - an amazing time saver.
I just wonder if there is a way to exit from browser-refresh through some script code. I've tried process.exit
or process.send('exit')
which exits the app but not the launcher. Any idea what else could work?
This bit of code opens up a new window when the server starts up:
if (process.send) {
process.send({ event: 'online', url: 'http://localhost:3131/' });
}
When I change my code, it restarts (as it should). However it does not use the window which was opened when the server initially started up. So every time I make an adjustment the server restarts and a new window in my browser is opened. This results in quite a few windows being opened and consuming system resources.
Is this expected behavior? If so, how does one use the process.send('online');
instead when the initial window has been started via process.send({ event: 'online', url: 'http://localhost:3131/' });
?
In my node application, I use jade template, and when some file changed the terminal will log 'Refresh triggered', bug what I see is the web page does not refresh actually. I do not know why
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.