Coder Social home page Coder Social logo

livereactload's Introduction

LiveReactload

Live code editing with Browserify and React.

❗ ❗ ❗

ATTENTION! The upcoming 4.x version will be using the new react-hot-loader and it is already available in npm as a beta tag. If you want to test it, check out the migration guide and installation instructions here!

❗ ❗ ❗

Gitter npm version Build Status

Motivation

Hot reloading is de facto in today's front-end scene but unfortunately there isn't any decent implementation for Browserify yet. This is shame because (in my opinion) Browserify is the best bundling tool at the moment.

Hence the goal of this project is to bring the hot reloading functionality to Browserify by honoring its principles: simplicity and modularity.

How it works?

LiveReactload can be used as a normal Browserify plugin. When applied to the bundle, it modifies the Browserify bundling pipeline so that the created bundle becomes "hot-reloadable".

  • LiveReactload starts the reloading server which watches the bundle changes and sends the changed contents to the browser via WebSocket.
  • When the changes arrive to the browser, LiveReactload client (included automatically in the bundle) analyzes the changes and reloads the changed modules

Starting from version 2.0.0 LiveReactload utilizes Dan Abramov's babel-plugin-react-transform and react-proxy, which means that hot-reloading capabilities are same as in Webpack.

And because one photo tells more than a thousand words, watch this video to see LiveReactload in action.

Other implementations

If you are a Webpack user, you probably want to check react-transform-boilerplate.

If you want to stick with browserify, but use the Hot Module Reloading API (like webpack), you could use: browserify-hmr, babel-plugin-react-transform and react-transform-hmr

Usage

Pre-requirements

LiveReactload requires watchify, babelify and react >= 0.13.x in order to work.

Installation (Babel 6.x)

Install pre-requirements (if not already exist)

npm i --save react
npm i --save-dev watchify

Install babelify and its dependencies

npm i --save babelify babel-preset-es2015 babel-preset-react

Install React proxying components and LiveReactload

npm i --save-dev livereactload [email protected] babel-plugin-react-transform

Create .babelrc file into project's root directory (or add react-transform extra if the file already exists). More information about .babelrc format and options can be found from babel-plugin-react-transform.

{
  "presets": ["es2015", "react"],
  "env": {
    "development": {
      "plugins": [
        ["react-transform", {
          "transforms": [{
            "transform": "livereactload/babel-transform",
            "imports": ["react"]
          }]
        }]
      ]
    }
  }
}

And finally use LiveReactload as a Browserify plugin with watchify. For example:

node_modules/.bin/watchify site.js -t babelify -p livereactload -o static/bundle.js

That's it! Now just start (live) coding! For more detailed example, please see the basic usage example.

Reacting to reload events

Ideally your client code should be completely unaware of the reloading. However, some libraries like redux require a little hack for hot-reloading. That's why LiveReactload provides module.onReload(..) hook.

By using this hook, you can add your own custom functionality that is executed in the browser only when the module reload occurs:

if (module.onReload) {
  module.onReload(() => {
    ... do something ...
    // returning true indicates that this module was updated correctly and
    // reloading should not propagate to the parent components (if non-true
    // value is returned, then parent module gets reloaded too)
    return true
  });
}

For more details, please see the redux example.

How about build systems?

LiveReactload is build system agnostic. It means that you can use LiveReactload with all build systems having Browserify and Watchify support. Please see build systems example for more information.

When does it not work?

Well... if you hide your state inside the modules then the reloading will lose the state. For example the following code will not work:

// counter.js
const React = require('react')

let totalClicks = 0

export default React.createClass({

  getInitialState() {
    return {clickCount: totalClicks}
  },

  handleClick() {
    totalClicks += 1
    this.setState({clickCount: totalClicks})
  },


  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Increment</button>
        <div>{this.state.clickCount}</div>
      </div>
    )
  }
})

Configuration options

You can configure the LiveReactload Browserify plugin by passing some options to it (-p [ livereactload <options...> ], see Browserify docs for more information about config format).

Available options

LiveReactload supports the following configuration options

--no-server

Prevents reload server startup. If you are using LiveReactload plugin with Browserify (instead of watchify), you may want to enable this so that the process won't hang after bundling. This is not set by default.

--port <number>

Starts reload server to the given port and configures the bundle's client to connect to the server using this port. Default value is 4474

--host <hostname>

Configures the reload client to use the given hostname when connecting to the reload server. You may need this if you are running the bundle in an another device. Default value is localhost

--no-dedupe

Disables Browserify module de-duplication. By default, de-duplication is enabled. However, sometimes this de-duplication with may cause an invalid bundle with LiveReactload. You can disable this de-duplication by using this flag.

--no-client

Omits the reload client from the generated bundle.

--ssl-cert <certFilename> and --ssl-key <privateKeyFilename>

Adds your custom SSL certificate and key to the reload web-server. This is needed if you want to use LiveReactLoad in HTTPS site. Parameters are paths to the actual files.

--no-babel

If you use a tool other than Babel to transform React syntax, this disables the in-browser warning that would otherwise appear.

--moduledir <node_modules>

Directory pointing node modules where livereactload is installed. By default points to <root-dir>/node_modules.

License

MIT

Contributing

Please create a Github issue if problems occur. Pull request are also welcome and they can be created to the development branch.

livereactload's People

Contributors

alexeyraspopov avatar bassjacob avatar boblauer avatar cguinnup avatar cheapsteak avatar djblue avatar djebbz avatar eugenez avatar fozzle avatar gaearon avatar hiddentao avatar iamdoron avatar kdonovan avatar liolaarc avatar mattdesl avatar milankinen avatar nestortejero avatar petetnt avatar pixelass avatar systemparadox avatar tec27 avatar tkurki avatar vicapow avatar vweevers avatar weiland 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

livereactload's Issues

lrApi.onReload callback fired only the first time

Hi,

I manage all of my state outside of React as a global json object (no this.setState() is used).

My app is split in app.js and appLibs.js. I want hot reload for stuff in app.js, not libs.

My app.js contains:

console.error("app reloaded!");
LiveReactLoadApi.onReload(function() {
    console.error("test");
});

When app is launched, it prints app reloaded!
When I modify something, it prints test
When I remodify one or many times something, it prints nothing.

But it reloads an app.js file on every change (and call forceUpdate client method).

It seems on the subsequent calls to executeReloadCallbacks I have 0 registered callbacks.
Also I'm surprised that it does not print app reloaded! on every app.js reload.

I tried to put LiveReactLoadApi on the lib bundle so that it is not reloaded but it did not change anything.

Can you please document better how the lrApi.onReload should be used.
Should the lrApi be in the reloaded bundle?
Any idea why the callbacks are removed?

how to pass --no-server option with api?

Hello, i would like to try livereactload.
I'm using browserify with gulp and i have multiple bundles (app.js, vendor.js)
I need to start only one instance of server, with first bundle.

How can i specify "--noserver" option when using node api?
I have tried something like

b.plugin("livereactload", {"no-server": true});

but without success. Please tell me the correct way to pass this option.

Fix React injecting to the global modules

When using global modules that use React as a peer dependency (for example react-bootstrap), they are broken after the first reload.

The possible reason is that LiveReacload trasform function does not apply to the global modules, thus they get the fresh copy of React after each reload => React instances won't match anymore => JavaScript errors occur.

Possible fix: transform function must be defined as global (-g instead of -t). However, the current logic does not support global transformation (you'll get other errors). Transform logic must be modified so that it can be used as a global transform.

Invariant Violation on forceUpdate

I am setting up a project with livereactload and react-router. Initially the project loads correctly (livereactload starts up without problems, the page renders without errors, etc.).

The first change I make is reloaded correctly in the browser, but I also get the following message in the browser:

Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner 
can have refs. This usually means that you're trying to add a ref to a component that doesn't 
have an owner (that is, was not created inside of another component's `render` method). 
Try rendering this component inside of a new top-level component which will hold the ref.

invariant @ invariant.js:42
ReactOwner.addComponentAsRefTo @ ReactOwner.js:70
attachRef @ ReactRef.js:23
ReactRef.attachRefs @ ReactRef.js:39
attachRefs @ ReactReconciler.js:22
assign.notifyAll @ CallbackQueue.js:68
ON_DOM_READY_QUEUEING.close @ ReactReconcileTransaction.js:81
Mixin.closeAll @ Transaction.js:207
Mixin.perform @ Transaction.js:148
Mixin.perform @ Transaction.js:134
assign.perform @ ReactUpdates.js:95
flushBatchedUpdates @ ReactUpdates.js:175
ReactPerf.measure.wrapper @ ReactPerf.js:70
Mixin.closeAll @ Transaction.js:207
Mixin.perform @ Transaction.js:148
ReactDefaultBatchingStrategy.batchedUpdates @ ReactDefaultBatchingStrategy.js:66
enqueueUpdate @ ReactUpdates.js:215
enqueueUpdate @ ReactUpdateQueue.js:30R
eactUpdateQueue.enqueueForceUpdate @ ReactUpdateQueue.js:153
ReactComponent.forceUpdate @ ReactComponent.js:90
forceUpdateInstance @ force-update-app.js:36
forceUpdateRootInstances @ force-update-app.js:28
forceUpdateApplication @ force-update-app.js:8
(anonymous function) @ livereload-client.js:97

Any subsequent changes to code are not successfully made in the browser but I get repeats of the above error.

Any suggestions?

Not reloading?

Awesome stuff here. 👍

I'm trying to use http-server instead of express to serve some static index.html. For some reason this is not causing it to reload. I'm testing in the gulp example -- everything works fine with express.

Added my own index.html, removed server stuff from gulpfile, and used this command: http-server . -p 3000.

I am getting new client connected and sending reload request to 1 clients but no hot-reloads. Page renders fine and changes on hard refresh as expected.

Any ideas?

app.js?__livereactloadPreventCache=1432506868384 won't be served by many simple hosting solutions

Hi,

GET http://localhost:8080/app.js?__livereactloadPreventCache=1432506868384 net::ERR_CONNECTION_REFUSED

I host locally my SPA app with a simple function like:

function hostit(){
  PORT=${1:-'8080'}
  echo "Will try to host your directory $pwd at http://localhost:$PORT"
  python -m SimpleHTTPServer $PORT
  # http-server -a localhost -p $PORT --cors
}

Both SimpleHTTPServer and http-server seems to have issues when a queryString is added to the static file.

http://localhost:8080/app.js will be served, but not http://localhost:8080/app.js?xxx=yyy

It would be great if the querystring to prevent caching could be replaced with something else, or at least being able to bypass it would be great

Doesn't work with React-jss

Hey, I love this plugin! Definitely is one of my favorites when working with react.

Is there any chance you could take a look at what it would take to make it work with https://github.com/jsstyles/react-jss?

I'm guessing the problem is similar to your "When does it not work" example, but I'm not sure how to go about fixing it.

Also there already appears to be React Hot Loader support. Is it possible to conditionally add Livereactload support in a similar way? Seems like it would need to add livereactload-api as a dependency.

BrowserSync compatibility

Hey, thanks for this, I really would like to use hot reload with Gulp/Browserify and not Webpack.

I got notification working w/ watchify but the problem is it doesn't refresh the browser. I'm using Rails app with BrowserSync, not Express.

[20:58:50] 2458336 bytes written (1.00 seconds)
LiveReactload: sending reload request to 1 clients
Uncaught TypeError: Cannot read property '1' of null       livereload-client.js:24

Multiple Entry Points

I have a multi-page app that uses factor-bundle to split it out, is this something livereactload plans to support? Would I just have multiple monitor statements in gulp?

Loading React more than once is causing context issues w/ react-router.

Hope you can help or point me in the right direction, but I've been battling w/ this most of the day and finally realized it wasn't anything in my code. I took your 05 example and swapped out it with any example from here:

https://github.com/rackt/react-router/tree/master/examples

And it works fine on first render, but if you make a change I get a pretty horrendous message. Very much to do w/ context and the new way of handling things in React 0.13.

warning: owner-based and parent-based contexts differ (values: `2` vs `1`) for key (routeDepth) while mounting RouteHandler (see: http://fb.me/react-context-by-parent)
:3000/static/bundle.js:23498 Warning: Failed Context Types: Required context `router` was not specified in `Link`. Check the render method of `App`.
:3000/static/bundle.js:23498 Warning: owner-based and parent-based contexts differ (values: `undefined` vs `function (props, context) {
      // This constructor is overridden by mocks. The argument is used
      // by mocks to assert on what gets mounted.

      if ("production" !== process.env.NODE_ENV) {
        ("production" !== process.env.NODE_ENV ? warning(
          this instanceof Constructor,
          'Something is calling a React component directly. Use a factory or ' +
          'JSX instead. See: http://fb.me/react-legacyfactory'
        ) : null);
      }

      // Wire up auto-binding
      if (this.__reactAutoBindMap) {
        bindAutoBindMethods(this);
      }

      this.props = props;
      this.context = context;
      this.state = null;

      // ReactClasses doesn't have constructors. Instead, they use the
      // getInitialState and componentWillMount methods for initialization.

      var initialState = this.getInitialState ? this.getInitialState() : null;
      if ("production" !== process.env.NODE_ENV) {
        // We allow auto-mocks to proceed as if they're returning null.
        if (typeof initialState === 'undefined' &&
            this.getInitialState._isMockFunction) {
          // This is probably bad practice. Consider warning here and
          // deprecating this convenience.
          initialState = null;
        }
      }
      ("production" !== process.env.NODE_ENV ? invariant(
        typeof initialState === 'object' && !Array.isArray(initialState),
        '%s.getInitialState(): must return an object or null',
        Constructor.displayName || 'ReactCompositeComponent'
      ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));

      this.state = initialState;
    }`) for key (router) while mounting Link (see: http://fb.me/react-context-by-parent)
:3000/static/bundle.js:1896 Uncaught TypeError: Cannot read property 'makeHref' of undefined
:3000/static/bundle.js:23498 Warning: Failed Context Types: Required context `router` was not specified in `Link`. Check the render method of `App`.
:3000/static/bundle.js:23498 Warning: owner-based and parent-based contexts differ (values: `undefined` vs `function (props, context) {
      // This constructor is overridden by mocks. The argument is used
      // by mocks to assert on what gets mounted.

      if ("production" !== process.env.NODE_ENV) {
        ("production" !== process.env.NODE_ENV ? warning(
          this instanceof Constructor,
          'Something is calling a React component directly. Use a factory or ' +
          'JSX instead. See: http://fb.me/react-legacyfactory'
        ) : null);
      }

      // Wire up auto-binding
      if (this.__reactAutoBindMap) {
        bindAutoBindMethods(this);
      }

      this.props = props;
      this.context = context;
      this.state = null;

      // ReactClasses doesn't have constructors. Instead, they use the
      // getInitialState and componentWillMount methods for initialization.

      var initialState = this.getInitialState ? this.getInitialState() : null;
      if ("production" !== process.env.NODE_ENV) {
        // We allow auto-mocks to proceed as if they're returning null.
        if (typeof initialState === 'undefined' &&
            this.getInitialState._isMockFunction) {
          // This is probably bad practice. Consider warning here and
          // deprecating this convenience.
          initialState = null;
        }
      }
      ("production" !== process.env.NODE_ENV ? invariant(
        typeof initialState === 'object' && !Array.isArray(initialState),
        '%s.getInitialState(): must return an object or null',
        Constructor.displayName || 'ReactCompositeComponent'
      ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));

      this.state = initialState;
    }`) for key (router) while mounting Link (see: http://fb.me/react-context-by-parent)
:3000/static/bundle.js:10735 Uncaught TypeError: Cannot read property '_currentElement' of null

Basically what's happening is that on the second round I'm losing my context and it's blowing up react-router as it expects that. I digged further and realized that bundle.js is added again to the page on each livereload notify which may be the issue. I just came off of webpack dev b/c of some issues I had, but it seems like what is done there is very specific module loading and it seems like that is what is going on here, but again context is somehow not coming into play on livereactload refresh. However, maybe I'm missing something obvious?

Any help would be greatly appreciated! Thanks so much

Chris

example 02-redux cause error message when updating reducer

<Provider> does not support changing `store` on the fly.
It is most likely that you see this error because you updated
to Redux 2.x and React Redux 2.x which no longer hot
reload reducers automatically.
See https://github.com/rackt/react-redux/releases/tag/v2.0.0
for the migration instructions.

Fix reload client crash when bundle url has query parameters

Original issue #17.

BrowserSync generates url that contains query parameters when reload client tries to parse bundle url from the thrown stacktrace, it gets the following string:

 "Error
        at getScriptURL (http://localhost:3001/assets/app.js?body=1:1812:11)
        at WebSocket.module.exports.init.ws.onmessage (http://localhost:3001/assets/app.js?body=1:1803:17)"

Which causes the regex parser at livereload-client.js

Regex parser must be improved to accept also urls with query parameters.

Something went wrong with LiveReactload initialization

Hey,

I saw a issue with this message (#18) but I think I have a different situation.
I'm using react with react-router and react-bootstrap and I initially tried you gulp example but I got some errors from the react-bootstrap refs.
So I tried using livereactload as a global transform and I get "Something went wrong with LiveReactload initialization" 9 times on the initial load. It works after these warnings but I'm curious why!

This is my setup:

gulp.task('jswatch', function () {
    var bundler = browserify({
        entries: path.join(__dirname, '/app/scripts/main.js'),
        basedir: __dirname,
        insertGlobals: true,
        cache: {},
        debug: true,
        packageCache: {},
        fullPaths: true,
        transform: [['livereactload', { global: true }], 'reactify'],
        extensions: ['.jsx']
    });

    bundler = watchify(bundler);
    lrload.listen();

    var rebundle = function () {
        var stream = bundler.bundle();
        stream.on('error', $.util.log);

        stream
            .pipe(source('app.js'))
            .pipe(gulp.dest('.tmp/scripts'))
            .pipe(lrload.gulpnotify);
    };

    bundler.on('update', rebundle);
    return rebundle();
});

Thanks!

lrload.React.Component is undefined

I'm trying to setup livereactload, by following the readme, however, I see this in the firebug console when I make a change to the files:

TypeError: lrload.React.Component is undefined
lrload.React.Component.prototype.forceUpdate.call(instance._instance)

In the console that is running the watch.sh script I see:

LiveReactload: new client connected
745622 bytes written to static/bundle.js (0.22 seconds)
LiveReactload: sending reload request to 1 clients

I had to modify the watch.sh script a bit, I added --extension, and -t reactify, is it possible those are causing problems? Here is the full script:

{ { node_modules/.bin/watchify static/js/index.jsx --extension=.jsx -v -t reactify -t babelify -t livereactload -o static/bundle.js 1>&2; } 2>&1 \
  | while read result; do
    echo "$result"
    [[ "$result" =~ ^[0-9]+[[:space:]]bytes[[:space:]]written  ]] && node_modules/.bin/livereactload notify
  done
} &

node_modules/.bin/livereactload listen
wait

Edit
I just tried without the --extension=.jsx, same thing.

Add some kind of smoke tests

Some automatic regression testing is needed so that I don't have to check each example manually before releasing a new version. The tests don't need to be runnable headlessly - just some kind of command line script that uses (if necessary) for example browser extensions to ensure that livereloading works. Running that script is much quicker than clicking all the examples by hand. :)

What would be the best way to implement those tests? Any ideas?

Here are my initial thoughts:

  • Use examples as tests
  • Zombie/PhantomJS/Selenium?

Support patching non-React Component classes?

Hello,

I noticed that if I save objects using LrAPI's setState and then get them back on reload, methods that were changed do not get patched onto the existing objects.

For example;

class Foo {
     constructor(name) { this.name = name; }
     toString() { return this.name; }
}

let instances = [new Foo('a'), new Foo('b'), new Foo('c')];
instances.map(i => i.toString()); // ['a', 'b', 'c']

lrApi.setState(instances);
// patch toString to return this.name.toUppercase() which will trigger reload

// expect ['A', 'B', 'C'], but I get ['a', 'b', 'c'] instead
lrApi.getState().map(i => i()); 

new Foo('d').toString() // 'D', as expected

If this is not supported, I'd love to contribute to the project so that this could work, I just need some pointers.

"Unexpected token <" using babelify + livereactload

Hi all,

I'm trying to run livereactload with

watchify test.js -t babelify -t livereactload -o bundle.js -v

and monitor with

livereactload monitor bundle.js

But when I change a file and bundle re-builds, on the client I receive a command to apply changes, but during this process I got following error:

When I try to debug it, I see that for some reason it tries to process index.html and this error is about <!DOCTYPE html> string and every string with <>. What's wrong?

Fix broken reload propagation guards

If the reloaded module contains only React.Component exports, then the reloading should not propagate to its parent module. However, this is broken somehow and should be fixed asap.

Fix broken onReload hook

module.onReload hook is broken - it only takes the first given reload callback and uses it all the time so that second module reload has no effect anymore

Test React 0.12 support

Ensure that React 0.12 applications can be livereloaded too, possible bugs found:

  • #4 lrload.React.Component is undefined

sending reload request to 0 clients

Hi there, I would love to try this magic repo but I'm unable to connect browser to livereactload (probably)

Watchify is running and it's working fine

watchify app/scripts/app.js -o .tmp/scripts/bundle.js -v
1522078 bytes written to .tmp/scripts/bundle.js (11.65 seconds)
1522078 bytes written to .tmp/scripts/bundle.js (0.37 seconds)
1522078 bytes written to .tmp/scripts/bundle.js (0.24 seconds)

LiveReactLoader is also running fine

node_modules/.bin/livereactload monitor -n .tmp/scripts/bundle.js & wait
[1] 14407
LiveReactload: server listening in port 4474
LiveReactload: sending reload request to 0 clients
LiveReactload: sending reload request to 0 clients
LiveReactload: sending reload request to 0 clients

Chrome live-reload icon is black
cheap flights czech republic - anywhere at skypicker com 2015-04-29 16-57-14

Desktop notifications are working

But I'm still getting LiveReactload: sending reload request to 0 clients...

Any ideas how to debug this more?

Base64 decoding error in Safari

When I try to use live react reload in Safari, I get the error:

data:application/json;base64,BASE64 DATA HERE;
Failed to load resource: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -10.)

This stack overflow answer suggests that it is incorrect encoding that causes the error.

Firefox have no problems though.

Uncaught SyntaxError: Unexpected end of input

I tried to use the API as I manage all the state outside of React.

LiveReactLoadApi.onReload(function() {
    console.error("test");
});

The first time I edit a JSX it prints "test" and then it prints this error message:
Uncaught SyntaxError: Unexpected end of input

It seems to be on require lines like:

module.exports = GlobeIcon;
;require("livereactload/lib/browser/reloadify-exports")("/home/sebastien/Desktop/Stample-react/src/img/icons/globe.jsx", module);

or

;require("livereactload/lib/browser/reloadify-exports")("/home/sebastien/Desktop/Stample-react/src/repositories/reminderRepository.js", module);

Could it be related to this semicolon at the beginning?

CSP issue

Hi,

I'm using livereactload to develop an app for Firefox OS. Everything works pretty well, except when I want to try it on the emulator which enforce strict CSP.

I get this :

Error: call to Function() blocked by CSP
Content Security Policy: The page's settings blocked the loading of a resource at self ("script-src app://fdf9027e-8bff-463d-8b94-343146365fb2").

Which seems to be related to this code:

 // Create a proxy constructor with matching name
  var ProxyClass = new Function('getCurrentClass', 'return function ' + (InitialClass.name || 'ProxyClass') + '() {\n      return getCurrentClass().apply(this, arguments);\n    }')(function () {
    return CurrentClass;
  });

Would it be possible to remove the use of Function ?

Thanks !

Rewrites JS to DOM multiple times

It's way past my bed time at this point....so maybe some sleep would help me resolve this but I seem to be having issues with Babelify + BrowserSync + React-Router + LiveReactLoad. (Thanks BTW as this really lets us stick with Browserify)

It works fine on the first, but not on the second and so on same as: #43

I am new to LiveReactLoad....and I'm pretty sure it's not a React-Router issue, any help would be VERY appreciated. BTW if I find some time I might try to help with that magic bullet for React-router if I can :)

not reloading components with shared-root

I'm using react-router with shared-root for public/private paths.

// routes.js
<Route handler={App}>
    <Route handler={PublicApp}>
        <Route name="login" handler={LoginApp}/>
        <DefaultRoute handler={LoginApp}/>
    </Route>
    <Route handler={PrivateApp}>
        <Route name="dashboard" handler={DashboardApp}/>
        <DefaultRoute handler={DashboardApp}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
</Route>
//privateApp.js
var PrivateApp = React.createClass({
    contextTypes: {
        router: React.PropTypes.func
    },

    render: function () {
        return (
            <div>
                <Sidebar/>
                <Header/>
                <RouteHandler/> // <--- this
                <Footer />
            </div>
        );
    }
});

If I change anything on config.js or its direct child privateApp.js I get a hot reload, however if I edit any of the grandchild like dashboardApp the watchify task run and LiveReactload server log the reload to clients message but nothing changes on the page.

Something went wrong with LiveReactload initialization

Thanks for implementing this! Super excited to get it up and running.

Getting the following warning multiple times on page load:
Something went wrong with LiveReactload initialization. Reloading is not enabled.

screen shot 2015-03-31 at 11 31 26 am

Not quite sure how to debug. Here is my watch setup:

#
# Development and watch tasks.
#
dev: setup public/build/js/vendor.bundle.js
    @node_modules/.bin/parallelshell \
        'make watch-js' \
        'make watch-less' \
        'make livereactload-listen' \
        'make livereactload-notify' \
        'make live-reload' \
        'NODE_ENV=development node index.js | node_modules/.bin/garnish'

watch-less:
    @node_modules/.bin/nodemon \
        --quiet \
        --ext less \
        --watch client \
        --exec 'make less' \
        | node_modules/.bin/garnish

public/build/js/vendor.bundle.js:
    @node_modules/.bin/browserify \
        -r react \
        -r react/addons \
        -r react-router \
        -g uglifyify \
        -o public/build/js/vendor.bundle.js

watch-js:
    @node_modules/.bin/watchify client/main.jsx \
        -x react \
        -x react/addons \
        -x react-router \
        -t reactify \
        -t envify \
        -g livereactload \
        -o public/build/js/main.bundle.js \
        -dv

livereactload-notify:
    node_modules/.bin/nodemon \
        --quiet \
        --watch public/build/js \
        --ext js \
        --exec 'node_modules/.bin/livereactload notify'

livereactload-listen:
    node_modules/.bin/livereactload listen

live-reload:
    @node_modules/.bin/wtch --dir public --extension css \
     | node_modules/.bin/garnish

And the output after running make dev and changing a component:

life-events → make dev
node_modules/.bin/livereactload listen
node_modules/.bin/nodemon \
        --quiet \
        --watch public/build/js \
        --ext js \
        --exec 'node_modules/.bin/livereactload notify'
LiveReactload: server listening in port 4474
 info wtch: livereload running on 35729
 info app: started -> http://0.0.0.0:8080
LiveReactload: sending reload request to 0 clients
879136 bytes written to public/build/js/main.bundle.js (1.42 seconds)
LiveReactload: sending reload request to 0 clients
LiveReactload: new client connected
879141 bytes written to public/build/js/main.bundle.js (0.18 seconds)
LiveReactload: sending reload request to 1 clients

Everything looks like it's working, but no reloads are happening. I have caching disabled on the client so not sure if it's related to that. Anyway any insight is appreciated!

Uncaught RangeError: Maximum call stack size exceeded

Hi there,

I used your example 03-build-systems to create my own build system. Everything works great, except of case, when I am importing components from react-bootstrap package.

This error i produced by this plugin in code section

function initModules() {
  var allExports = window.__livereactload$$.exports;
  var modules = window.__livereactload$$.modules;
  // initialize Browserify compatibility
  Object.keys(modules).forEach(function (id) {
    modules[id][0] = function (require, module, exports) {
      if (typeof allExports[id] !== "undefined") {
        module.exports = allExports[id].exports;
      } else {
        var __init = new Function("require", "module", "exports", modules[id].source);
        var _require = function _require() {
          return require.apply(require, Array.prototype.slice.call(arguments).concat(id));
        };
        __init(_require, module, exports, arguments[3], arguments[4], arguments[5], arguments[6]);
      }
    };
    modules[id][1] = modules[id].deps;
  });
}

on line var __init = new Function("require", "module", "exports", modules[id].source);

I looked in react-boostrap module, and find out "strange way" of exporting node modules:

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
var _Alert2 = require('./Alert');
var _Alert3 = _interopRequireDefault(_Alert2);
exports.Alert = _Alert3['default'];

So I added browserify-shim to import non standard imports, but it still does not work.

Here is my repo (improved build system based on your example 03-build-systems) which easy to install and run:

  • repo: https://github.com/cidevant/tabula-rasa-build-system
  • install: make configure
  • run: make run

To invoke error, just uncomment line 3 in /src/scripts/init.js.

Thank you for your attention,

Cidevant

Reloading client WS hostname from bundle's host

Now the reloading client listens to reload events from localhost (with WebSocket). When WS client is established, the target hostname should be detected from the bundle's url (using same method as the actual reloading) instead of using hard coded localhost.

Rules:

  1. If hostname is set with a config variable, then use it
  2. If hostname is resolvable from the bundle script url, then use it
    • file:///... -> use localhost
    • others -> use bundle's hostname
  3. Otherwise, use localhost

Do not transform JSON files

When some module uses require('./some/file.json') then the bundle ends up to the SyntaxError. Original issue is #22.

Fix: do not transform JSON files.

browserSync compatibility

I got livereactload 0.4 to work with browserSync but since 0.5 isn't working at all.
Is it possible?

Hardware issues

Hello, I implemented example 05-build-systems (the exact same code), and it is slow but most probably because it is eating up my hardware.

Here is my gulpfile.js, maybe you can spot something fishy there.

screen shot 2015-05-20 at 22 51 23

module '' error and not sure how to debug

my old watch script

#!/bin/sh
watchify ./src/clients/www/index.js -t babelify -o ./src/clients/www/js/x.js

my new (hopefully soon!) reloading script

#!/bin/bash
index="./src/clients/www/index.js"
out="./src/clients/www/js/x.js"

node_modules/.bin/watchify $index -v -t babelify -g livereactload -o $out &
node_modules/.bin/livereactload monitor -n $out &
wait

😢 result:
screen shot 2015-07-23 at 2 37 38 pm

Reloading twice in Gulp build

Matti,
Thanks for this wonderful plugin. I've successfully implemented it in a test environment and it works great except I'm getting a log from a component's render method running twice when I re-save the file. You can grab a minimal test case of it here:

http://dev.reintroducing.com/2015/livereactload-test.zip

Just run npm i after you've unzipped that and then just run gulp. This runs a browser-sync server along with LRL. If you open your console you will see a log for TestComponent. Open that file in /js/components/TestComponents.jsx and re-save it. You will now see two more TestComponent logs in your console.

I can't pinpoint why this is happening. I can't tell if this is an issue with my setup and my Gulp tasks or if it's an issue with LRL. If you have a moment I'd appreciate you taking a look at what I've got going on in the gulp tasks and see if you can pinpoint where my issue is. The task gulp/tasks/default.js is what running gulp runs.

Thank you for any time you can dedicate to this.

Adding livereactload as global transform when no react peer causes error `module.exports=;` - ParseError: Unexpected token

In following the README it looked like the safe thing to do is to add livereactload as a global transform even though I am not using anything that has a peer dependency, so that if I were to add something later, it would already be set properly.

However in doing that I get a ParseError for the generated code module.exports=;

So apparently you can't use it as a global transform if you don't have any react peer dependencies.

Switching livereactload to a normal browserify transform fixes the problem.

I wonder if there is anyway this could be improved or at least have an informative error message.

/Users/jeff/working/react-iso-router-im-curs-rx3-transition-livereload/node_modules/browserify/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/primes.json:1
module.exports=;require=(function(req){if(typeof(window)!=="undefined"){return(function(name){if(name==="react")return(function(){window.__livereactload=window.__livereactload||{};window.__livereactload.React=window.__livereactload.React||req("react");return(window.__livereactload.React);})();if(name==="react/lib/ReactMount")return(function(){window.__livereactload=window.__livereactload||{};window.__livereactload.ReactMount=window.__livereactload.ReactMount||req("react/lib/ReactMount");return(window.__livereactload.ReactMount);})();if(name&&name.indexOf("react/")===0)return(function(name){window.__livereactload=window.__livereactload||{};window.__livereactload["__reactExport_"+name]=window.__livereactload["__reactExport_"+name]||req(name);return(window.__livereactload["__reactExport_"+name]);})(name);return(req(name));})}else{return(req(name));}})(require);{
               ^
ParseError: Unexpected token

It looks to me like the error is coming from module.exports=; (missing some value before the semicolon)

The browserify parts of my package.json are:

  "browser": "src/browser.jsx",
  "browserify": {
    "transform": [
      "babelify"
    ]
  },

My watchify command from my npm run watch

watchify . -d --extension=.jsx -g livereactload -v -o dist/bundle.js

Here are the versions of the packages I am using:

npm ls browserify watchify livereactload react babelify
[email protected] /Users/jeff/working/react-iso-router-im-curs-rx3-transition-livereload
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

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.