Giter Site home page Giter Site logo

react-transform-hmr's Introduction

This Project Is Deprecated

React Hot Loader 3 is on the horizon, and you can try it today (boilerplate branch, upgrade example). It fixes some long-standing issues with both React Hot Loader and React Transform, and is intended as a replacement for both. The docs are not there yet, but they will be added before the final release. For now, this commit is a good reference.

react-transform-hmr

react-transform channel on discord

A React Transform that enables hot reloading React classes using Hot Module Replacement API. Hot module replacement is supported natively by Webpack and available in Browserify with browserify-hmr.

🚧🚧🚧🚧🚧

This is highly experimental tech. If you’re enthusiastic about hot reloading, by all means, give it a try, but don’t bet your project on it. Either of the technologies it relies upon may change drastically or get deprecated any day. You’ve been warned 😉 .

This technology exists to prototype next-generation React developer experience. Please don’t use it blindly if you don’t know the underlying technologies well. Otherwise you are likely to get disillusioned with JavaScript tooling.

No effort went into making this user-friendly yet. The goal is to eventually kill this technology in favor of less hacky technologies baked into React. These projects are not long term.

Installation

First, install the Babel plugin:

npm install --save-dev babel-plugin-react-transform

Then, install the transform:

npm install --save-dev react-transform-hmr

React

Edit your .babelrc to include a plugin configuration for react-transform. It contains array of the transforms you want to use:

{
  "presets": ["es2015", "stage-0"],
  "env": {
    // only enable it when process.env.NODE_ENV is 'development' or undefined
    "development": {
      "plugins": [["react-transform", {
        "transforms": [{
          "transform": "react-transform-hmr",
          // if you use React Native, pass "react-native" instead:
          "imports": ["react"],
          // this is important for Webpack HMR:
          "locals": ["module"]
        }]
        // note: you can put more transforms into array
        // this is just one of them!
      }]]
    }
  }
}

Make sure you process files with babel-loader, and that you don’t use React Hot Loader (it’s not needed with this transform).

It is up to you to ensure that the transform is not enabled when you compile the app in production mode. The easiest way to do this is to put React Transform configuration inside env.development in .babelrc and ensure you’re calling babel with NODE_ENV=production. See babelrc documentation for more details about using env option.

Warning! This doesn't currently work for stateless functional components that were introduced in React 0.14!

React Native

This transform enables hot reloading when used together with React Native Webpack Server. However note that you should not use .babelrc to configure it with React Native. Otherwise you’ll get Uncaught SyntaxError: Unexpected reserved word in ActivityIndicatorIOS.ios.js.

There are two problems why .babelrc doesn’t work well in React Native:

Until we have better .babelrc support in React Native, you should configure React Transform together with babel-loader:

var fs = require('fs');
var path = require('path');
var webpack = require('webpack');

var config = {
  debug: true,

  devtool: 'source-map',

  entry: {
    'index.ios': ['./src/main.js'],
  },

  output: {
    path: path.resolve(__dirname, 'build'),
    filename: '[name].js',
  },

  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        stage: 0,
        plugins: []
      }
    }]
  },

  plugins: []
};

// Hot mode
if (process.env.HOT) {
  config.devtool = 'eval';
  config.entry['index.ios'].unshift('react-native-webpack-server/hot/entry');
  config.entry['index.ios'].unshift('webpack/hot/only-dev-server');
  config.entry['index.ios'].unshift('webpack-dev-server/client?http://localhost:8082');
  config.output.publicPath = 'http://localhost:8082/';
  config.plugins.unshift(new webpack.HotModuleReplacementPlugin());

  // Note: enabling React Transform and React Transform HMR:
  config.module.loaders[0].query.plugins.push([
    'react-transform', {
      transforms: [{
        transform : 'react-transform-hmr',
        imports   : ['react'],
        locals    : ['module']
      }]
    }
  ]);
}

if (process.env.NODE_ENV === 'production') {
  config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
  config.plugins.push(new webpack.optimize.UglifyJsPlugin());
}

module.exports = config;

See React Native Webpack Server examples for details.

License

MIT

react-transform-hmr's People

Contributors

avindra avatar catamphetamine avatar gaearon avatar ianstormtaylor avatar jamiebuilds avatar molily avatar vincentfretin avatar

Stargazers

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

Watchers

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

react-transform-hmr's Issues

Changing state does hot reload

Node: 5.3.0
presets: ["react", "es2015", "stage-0"],

class App extends Component {
  state = {msg: "myMsg"}

  render() {
    return (
      <div>
        <h1>{this.state.msg}</h1>
      </div>
    );
  }
}

Changing myMsg does not hotreload, mapping it to a variable outside the class does.

Migrating from webpack-hmr, Error: locals[0] does not appear to be a `module`

When migrating from a working implementation with react-transform-webpack-hmr to react-transform-hmr I get the following error:

Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr

Here is the .babelrc file I'm using:

{
  "stage": "0",
  "env": {
    "production": {
      "plugins": [
        "react-require",
        "dead-code-elimination"
      ],
    },
    "development": {
      "plugins": [
        "react-transform",
        "react-require"
      ],
      "extra": {
        "react-transform": [{
          "target": "react-transform-hmr", // changed from react-transform-webpack-hmr
          "imports": ["react"],
          "locals": ["module"]
        }, {
          "target": "react-transform-catch-errors",
          "imports": ["react", "redbox-react"]
        }]
      }
    }
  }
}

PhantomJS Hangs

I'm having troubles getting PhantomJS to work with the react transform boilerplate. When I run it with Chrome all tests pass but if I run it with Phantom it just hangs with [HMR] connected.

Have you ever ran into this before? Any ideas for troubleshooting would be most helpful!

Here's the full debug info if it's helpful:

acceptance|master⚡ ⇒ be rspec

Randomized with seed 56835
D: [11/05/15 21:31:13][tests] - Executing tests with this configuration:

---
BROWSER: phantomjs
BASE_URL: http://localhost:3000

D: [11/05/15 21:31:13][tests] -
D: [11/05/15 21:31:13][tests] - =============================
D: [11/05/15 21:31:13][tests] - Starting test: Page: Overview should have overview heading
D: [11/05/15 21:31:13][tests] - From file    : ./spec/pages/overview_spec.rb
D: [11/05/15 21:31:13][tests] - -----------------------------
[HMR] connected
D: [11/05/15 21:33:19][tests] -
D: [11/05/15 21:33:19][tests] - -----------------------------
D: [11/05/15 21:33:19][tests] - Completed test: Page: Overview should have overview heading
D: [11/05/15 21:33:19][tests] - From file     : ./spec/pages/overview_spec.rb
D: [11/05/15 21:33:19][tests] - Result        : Fail - RSpec::Core::MultipleExceptionError
D: [11/05/15 21:33:19][tests] - =============================

Cheers!

The following modules couldn't be hot updated: (Full reload needed)

With some of my components I'm getting the following message all the time.

[HMR] The following modules couldn't be hot updated: (Full reload needed)
app.js:839 [HMR]  - ./~/css-loader?sourceMap&modules&localIdentName=[name]--[local]--[hash:base64:5]!./~/postcss-loader!./app/styles/Tag.css

Any idea why this might happen? Below is the source of my component and its stylesheet.

import { PropTypes } from 'react'
import cx from 'classnames'
import s from 'styles/Tag'


Tag.propTypes = {
  selected: PropTypes.bool.isRequired,
  label: PropTypes.string.isRequired,
  onClick: PropTypes.func.isRequired
}

export default function Tag({selected, label, onClick}) {

  const classes = cx(s.main, {
    [s.selected]: selected
  })

  return (
    <span className={classes} onClick={onClick}>{label}</span>
  )
}
@import 'variables/all';

.main {
  height: 1.5em;
  background-color: var(--color-white);

  line-height: 1;
  text-align: center;
  vertical-align: middle;
  padding: 0.2em;

  border: 1px solid var(--color-gray);

  &.selected {
    background-color: var(--color-gray);
    color: var(--color-white);
  }
}

Undocumented eependency on es2015 transforms

@gaearon, thanks for your remarkable work on this project. I know you have a lot on your plate right now, so this is a heads-up, not a complaint.

react-transform-hmr will not work without the following babel plugins enabled:

  1. transform-es2015-modules-commonjs
  2. transform-es2015-classes

# 1 is because the code react-transform-hmr generates includes ES6-style imports. Ideally these should be pre-compiled to CommonJS (with option for AMD).

# 2 is trickier - it looks like internals of the HMR transform depend on some implementation detail of Babel's class implementation. Running against Chrome without the es6 transform does not work, even though Chrome has native support for es6 classes.

Class property function will not be patched

A simple example:

  render() {
    return (<div onClick={this.log} >{'foo'}</div>);
  }

  log = function() {
    console.log('foo');
  }

(property function needs Babel stage 0)

The change inside render function can HMR, however, the change inside log function will not HMR.

It seems react-transform-hmr only patch the function at proto, but not at the object instance.

For react on ES6+, class property function mainly used with arrow function to provide 'this' binding. See example at http://babeljs.io/blog/2015/06/07/react-on-es6-plus/

So I suppose it's better to fix this bug.

For now, a work around way is not use class property function, but just use function bind at constructor.

I'll try to figure out a fix if I have time next week.

Full page reload instead of hot reload

I met this error and have no idea how to solve it. Could you please help me with that ?
[HMR] Cannot apply update. Need to do a full reload!
[HMR] Error: Aborted because 129 is not accepted

components don't seem to be hot reloading changes to action creators

I have the following action in actions.js:

export function reorderBlocks(viewId, newOrder) {
  return {
    type: REORDER_BLOCKS,
    payload: newOrder,
    meta: {
      context,
      viewId,
    },
  };
}

It's used by ReduxDashboardView.jsx:

import {
  reorderBlocks, 
  ...
} from './actions';

class ReduxDashboardView extends Component {
  ...
  onReorderFinished = () => {
    let {model} = this.state;
    let viewId = model.get('_id');
    let newOrder = model.getIn(['data', 'blocks']).map(block => block.get('_id')).toArray();
    this.props.dispatch(reorderBlocks(viewId, newOrder));
  }
  render() {
    let {model} = this.state;
    let {onReorderBlocks, onReorderFinished, onResizeBlock, onResizeFinished} = this;
    return <DashboardView {...this.props} model={model}
      onReorderBlocks={onReorderBlocks} onReorderFinished={onReorderFinished}
      onResizeBlock={onResizeBlock} onResizeFinished={onResizeFinished}/>;
  }
}

Now if I add console.log('test'); at the top of reorderBlocks and save, the browser appears to indicate that everything has been hot updated, yet when I trigger the action again, it doesn't print to console. But when I refresh the page and trigger the action again, it does print to console.

I had assumed what would happen in this case is that the react-transform-hmr wrapper for the parent of ReduxDashboardView ends up re-requiring ReduxDashboardView.jsx (which requires the new actions.js in turn) and mounts a completely new <ReduxDashboardView> that can call the new reorderBlocks. But I'm guessing that's not what happens -- is it impossible for react-transform-hmr to hot reload in this case or am I doing something wrong?

Firefox issue: TypeError: Not allowed to define a non-configurable property on the WindowProxy object

Since I added this transformation, I am getting this issue on Firefox Nightly, which is completely breaking my rendering (note: works on Chrome and Safari)
Any idea ?

Seems related to

I pasted some clues, but to be honest, 🐶 "I don't know what I am doing".

Hot module replacement should trigger render ?

I have a setup with webpack and react-transform-hmr, I managed to make it work correctly, i.e. when changing a component, I get the expected:

[HMR] bundle rebuilding
[HMR] bundle rebuilt in 1780ms
[HMR] Checking for updates on the server...
[HMR] Updated modules:
[HMR]  - ./src/containers/App.js
[HMR]  - ./src/routes.js
[HMR]  - ./src/bin/client.js
[HMR] App is up to date.

However, this doesn't trigger a rerender of the components, therefore making it less useful.

Is that the expected behaviour anyway ? Or am I missing something ?

Is there an issue with react-router

I started playing around with the counter example of redux and added some things. One of those additions was react router.

I have also changed some other things, so I am not 100% sure that this is the issue, but I realized that now my hot reloading is not working anymore.

I have also seen that it does not work in the real-world example.
reduxjs/redux#832

Does react-transform-hmr support pure function components

I'm not having any luck getting components defined as a pure function to hot-reload. The component in question:

export default function Light (props) {
  const { light, toggleLight, id } = props
  const status = light.state.on ? 'one' : 'off'

  return (
    <div>{light.name}
      <button onClick={() => toggleLight({ ...light, id })}>
        {status}
      </button>
    </div>
  )
}

I get this error in the console:

[HMR] Updated modules:
(index):25734 [HMR]  - ./app/components/light.js
(index):25734 [HMR]  - ./app/components/lights.js
(index):25739 [HMR] App is up to date.
(index):15049 Uncaught TypeError: Cannot read property '__reactAutoBindMap' of null

Is this scenario supposed to work? Any idea what I'm doing wrong? Let me know if more context is needed.

Cannot transform ES6 React class

If I do not transpile down ES6 classes to ES5, I received:

Class constructors cannot be invoked without 'new'

Basically I have to use babel-plugin-transform-es2015-classes, even though Node.js and modern browsers already have support for ES6 classes.

Is there some way to work around this?

Cannot find update (Full reload needed)

Having some bother getting this up and running. I'm using the babel 6 beta. It connects ok, and registers a changed file, but when it comes to the crunch we get:

GET http://localhost:3010/static/5c86957e12d231184053.hot-update.json 404 (Not Found)hotDownloadManifest @ bootstrap 5c86957e12d231184053:522hotCheck @ bootstrap 5c86957e12d231184053:706check @ process-update.js:30module.exports @ process-update.js:26processMessage @ client.js?101f:115handleMessage @ client.js?101f:63
process-update.js:35 [HMR] Cannot find update (Full reload needed)
process-update.js:36 [HMR] (Probably because of restarting the server)

my webpack:

var path = require("path"),
  autoprefixer = require("autoprefixer"),
  ExtractTextPlugin = require("extract-text-webpack-plugin"),
  webpack = require("webpack");


var definePlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.NODE_ENV === "development"))
});

module.exports = {
  context: path.join(__dirname, "../src"),
  entry: [
    'webpack-hot-middleware/client?path=http://localhost:3001/__webpack_hmr',
    "./client/index.es6"
  ],
  resolve: {
    extensions: ["", ".webpack.js", ".web.js", ".js", ".es6", ".jsx", ".less", ".css", ".json"]
  },
  output: {
    path: path.join(__dirname, "../build"),
    filename: "app.js",
    publicPath: "/static/"
  },
  devtool: "#source-map",
  module: {
    loaders: [{
      test: /(.es6|.jsx)/,
      loader: "babel",
      exclude: /node_modules/,
      query: {
        presets: ["es2015", "react", "stage-1"],
        plugins: [
            ["react-transform", {
              transforms: [{
                transform: "react-transform-hmr",
                imports: ["react"],
                locals: ["module"]
              }]}
            ]
        ]
        // optional: ["runtime"]
      },
      exclude: /node_modules/
    }, {
      test: /\.less$/,
      loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader!less-loader")
    }, {
      test: /\.(png|woff|woff2|eot|ttf|svg)$/,
      loader: "url-loader?limit=100000"
    }]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin("app.css", {
      allChunks: true
    }),
    definePlugin
  ],
  postcss: [autoprefixer]
};

my devserver:

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./development');

var app = express();
var compiler = webpack(config);

app.use(function(req, res, next) {
  res.set("Access-Control-Allow-Origin", "*");
  next();
});

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

// app.get('*', function(req, res) {
//   res.sendFile(path.join(__dirname, 'index.html'));
// });

app.listen(3001, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3001');
});

Wrapped components have no setState in IE9

Basically wrapped components seem to be missing their setState method. Might be an issue with react-proxy and not react-transform-hmr... Tested on IE9. Here's a repo with a minimal repro case: https://github.com/kentor/react-transform-hmr-ie9.

I also get the Warning message "Something is calling a React component directly. Use a factory or JSX instead."

screen shot 2015-09-22 at 10 28 19 am

Other info:

  • Don't get this issue in Chrome or Firefox.
  • Don't think browserify-hmr is the problem. Same thing with webpack using the babel transform.
  • Did not get this with react-hot-loader

@gaearon do you know what could cause this on top of your head? if not I can look into it some time tomorrow

Trying to set "render" as property of current state breaks hmr

So, trying to do this.setState({render: 'val'}); breaks HMR errors wrapper (not 100% sure that's the correct place to report, feel free to close/point me to the right repo).

How to reproduce:

  1. Clone react-transform-boilerplate
  2. Change method tick() in App.js to the following:
tick() {
    this.setState({
        render: 'whatever',
        counter: this.state.counter + this.props.increment
    });
}

You will see the following error in the console:

Uncaught TypeError: Cannot read property 'prototype' of undefined
    wrapToCatchErrors @ index.js?9778:32

Adjusting the code just a bit makes it work fine, e.g.:

tick() {
    const s = {
        render: 'whatever',
        counter: this.state.counter + this.props.increment
    };
    this.setState(s);
}

It seems that render property gets parsed incorrectly in some place along the way.

Class properties do not hot reload ?

In the context of a export default class Random extends React.Component {

With

    render() {
      return(
        {this.renderTest()}
        {this.renderTest3()}
     );
   }
    renderTest()
    {
      return <Button>I will hot reload</Button>;
    }

Works for hot reloading but

    renderTest3 = () => {
      return <Button>I will fail.</Button>;
    };

Will never get hot reloaded when changing the string. Is it a desired behavior ?

We get the [React Transform HMR] Patching Builder process-update.js?e13e:75 [HMR] Updated modules: process-update.js?e13e:77 [HMR] - ./app/components/Random.jsx process-update.js?e13e:82 [HMR] App is up to date.

And the corresponding webpackHotUpdate gets fetched, but the page stays the same.

.babelrc plugins:

"presets": ["stage-0","react", "es2015"],
  "plugins": [
    "syntax-class-properties",
    "syntax-decorators",
    "syntax-object-rest-spread",
    "transform-class-properties",
    "transform-decorators-legacy",
    "transform-object-rest-spread",
  ]

versions:

    "babel-plugin-react-transform": "^2.0.0",
    "babel-plugin-transform-class-properties": "^6.3.13",
    "babel-plugin-transform-decorators": "^6.3.13",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-es2015-classes": "^6.3.15",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.3.16",
    "babel-plugin-transform-object-rest-spread": "^6.3.13",

Could it be because it's a stage0 feature according to https://github.com/jeffmo/es-class-fields-and-static-properties ?

locals[0] does not appear to be a `module` object...

...../react-transform-boilerplate/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a module object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using env section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');

I'm trying server-side rendering and I use react-transform-hmr to do hot reload, but when I import react components to the script, the error above is thrown.

I followed react-transform-boilerplate and simply add a line to the top of the devServer.js:

var App = require('./src/App');
...

then run the script with babel-node:

"start": "babel-node devServer.js"

and you will see the problem. So how can I use this plugin to do server-side rendering?

File depth limit

Is there a depth limit for files that trigger a webpack rebundling? In our project, we have a rather deep file structure. E.g., common/components/App/index.js triggers rebundling, but common/components/icons/Icon/index.js does not.

Hot Reload Electron

Do you think there's a way to use this with Electron, without Browserify or Webpack, relying on the chrome-remote-interface? That's what electron-hot uses, which works quite well for pure functions. About to try it with React.

Full reload when declaring render as class property arrow function

We've been breaking our heads on an issue where a full reload is triggered on a change within the render method of a React component, with the warning: "[HMR] The following modules couldn't be hot updated: (Full reload needed)".

After a lot of fiddling with the source, and stripping it down to the bare basics, we came to the conclusion that using class properties with arrow functions causes the issue. It is reproducible in react-transform-boilerplate with this simple change.

In the boilerplate app, the issue only seems to pop up when changing the render function of the root component. In our own app, changing the definition of any function causes a full reload when changing something inside that function.

I'm not so sure that I'm filing this issue on the correct project. Please 302 me if necessary.

Doesn't work with react-jss

I'm trying to make basic app setup with react-jss and it doesn't seem to be working with react-transform-hmr, however hmr works well with everything else. Actually, hot-update file is loaded and it contains updated style, but seems that stylesheet is not replaced after.
I use ES6 classes for component definition and ES7 decorator @useSheet for applying higher-order react-jss component, if it can help with investigation.
Thnx in advance.

Server-side rendering

When you compile your server with babel-node and render React Components on the server you will get the following error message:

/Users/nikgraf/Projects/time/node_modules/react-transform-hmr/lib/index.js:54
    throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
    ^

Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
    at proxyReactComponents (/Users/nikgraf/Projects/time/node_modules/react-transform-hmr/lib/index.js:54:11)
    at Object.<anonymous> (/Users/nikgraf/Projects/time/src/containers/Index.js:5:67)
    at Module._compile (module.js:434:26)
    at normalLoader (/Users/nikgraf/Projects/time/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/nikgraf/Projects/time/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/nikgraf/Projects/time/src/routes.js:8:35)
22 Sep 21:55:38 - [nodemon] app crashed - waiting for file changes before starting...

It's happening due this change: 9afec1b

Ideally you want to avoid transforming on the server. Babel uses the existing .babelrc by default. There are several solutions I can imagine:

  1. Split the server into the webpack and the render part and proxy the rendering endpoint. In case babel-node would allow babelrc option you could provide an alternative .babelrc.
  2. Don't return an error and make it noop again 😄

Did I miss something? I'm happy to contribute, but I wasn't sure whats your opinion?

P.S: I went for the proxy solution as I want to run the rendering server with nodemon anyway but avoid webpack from restarting continuously. I worked around it by setting BABEL_ENV="developer-client"only for the webpack process and also use "developer-client" in .babelrc.

Remove console.info?

I'm not sure to understand the use case of this console.info(...).
It's adding noise to my console. What do you think about removing it or adding a way do disabling it?

module.exports now throwing "Unexpected indentifier" error at runtime

This happens on on dev environment, and only at runtime. And only for ES6 classes (not React.createClass components) being used in redux-forms.

class GiftCodeForm extends React.Component {
...
}
...
module.exports = connectReduxForm({
    form: 'gift_code_form', 
    fields: ['code'],
    validate: validateForm
})(GiftCodeForm);
module.exports = GiftCodeForm;

I'm using babel6 and the new babel-react-transform. If I remove react-transform-hmr from .babelrc, error goes away.

Here's the .bablerc:

{
  "presets": ["es2015", "react", "stage-0"],
  "env": {
    "development": {
      "plugins": [
        ["react-transform", {
          "transforms": [{
            "transform": "react-transform-hmr",
            "imports": ["react"],
            "locals": ["module"]
          }, {
            "transform": "react-transform-catch-errors",
            "imports": ["react", "redbox-react"]
          }]
        }]
      ]
    }
  }
}

Configuration / support for babel 6.x?

I just tried upgrading to babel 6 and I'm getting the following error:

Module build failed: ReferenceError: [BABEL] client/lib/app.jsx: Unknown option: client/.babelrc.env.development.extra

Apparently babel 6 has changed their configuration options. This isn't a bug in react-transform-hmr per se but at least the README documentation will need to be updated to the new option format. If I can figure it out I will post here.

Not working with material-ui

When changing a file with material-ui components, hmr didn't happen.

FYI, files following

index.jsx

import React from 'react'
import { render } from 'react-dom'

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

import Hello from './components/hello'
render(<Hello />, document.getElementById('root'))

hello.jsx

import React from 'react'
import RaisedButton from 'material-ui/lib/raised-button'

class Hello extends React.Component {
  render() {
    return <RaisedButton label="submit" />
  }
}

export default Hello

.babelrc

{
  "presets": ["react", "es2015"],
  "env": {
    // this plugin will be included only in development mode, e.g.
    // if NODE_ENV (or BABEL_ENV) environment variable is not set
    // or is equal to "development"
    "development": {
      "plugins": [
        // must be an array with options object as second item
        ["react-transform", {
          // must be an array of objects
          "transforms": [{
            // can be an NPM module name or a local path
            "transform": "react-transform-hmr",
            // see transform docs for "imports" and "locals" dependencies
            "imports": ["react"],
            "locals": ["module"]
          }]
          // by default we only look for `React.createClass` (and ES6 classes)
          // but you can tell the plugin to look for different component factories:
          // factoryMethods: ["React.createClass", "createClass"]
        }]
      ]
    }
  }
}

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    './public/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [{
      test: /\.jsx?/,
      loaders: ['babel'],
      include: path.join(__dirname, 'public')
    }]
  },
  resolve: {
    extensions: ["", ".js", ".jsx"]
  }
};

File/Program node, we can't possibly find a statement parent to this

Trying to integrate this into a project, but the plugin complains that it cannot find parents for certain files.

@gaearon Is there a certain structure which i need to follow? Do I still need a single top level react component which then imports my routes etc.?

Sorry if this issue does not actually belong here - was not sure whether to post here or on the repo for the babel plugin.

Requiring unknown module "react-transform-webpack-hmr"

Hey, first, thanks for all of your great projects! They've saved me so much time, and I've learned a ton from them.

So, onto the issue:

I've been transitioning various projects from react-hot-loader to react-transform-webpack-hmr, and it's gone without a hitch on React web projects. I've been trying it out on my react-native projects, where I'm running react-native-webpack-server. I followed your basic instructions in this issue, along with the boilerplate setup, but for some strange reason, I always get this error in the iOS simulator:

Requiring unknown module "react-transform-webpack-hmr"

http://localhost:8080/index.ios.bundle:23569 ...

screenshot_9_15_15__1_58_pm

I realize that I'm very likely barking up the wrong tree (and I apologize if that's the case), but I've tried working around this from every angle I can think of, so I wanted to see if this is something you've seen before and whether there's a fix I'm not aware of.

Again, thank you for all your work!

Update: I should note the obvious: I do have the module installed, and I've removed and re-installed it several times, and likewise restarted the packager, just to sanity check myself.

TypeError: Not allowed to define a non-configurable property on the WindowProxy object

Hi @gaearon, just wanted to say thanks for everything you're working on, really awesome stuff and really pushing things forward!

After trying to run the react-transform-boilerplate, I think I managed to narrow down the component at fault to this transform. The error is occurring in Firefox Developer Edition, version 42, and it seems as though the bundle is prevented from executing completely with the following message:

TypeError: Not allowed to define a non-configurable property on the WindowProxy object

This does not occur in Chrome 45. Unfortunately Firefox seems unable to map the eval'd line numbers back to source at all, making debugging pretty difficult...

Babel's Class Call Check vs IE10

When running a react-transform-hmr-enabled application in IE10, you will get Class Call Check ("Cannot call a class as a function") errors from Babel and React components will fail to render. This seems to occur when calling React.render on an ES6 class. This might be a problem in react-proxy, but react-transform-hmr is as much as I could isolate it.

Note that IE10 is probably not going to support hot loading in most setups (it doesn't support Server-Sent-Events, which at least webpack-hot-middleware uses), so this is more of an inconvenience than a blocker; I have to completely turn off HMR and restart the Webpack server to test in IE10, rather than it failing gracefully.

How to disable for server side rendering?

When doing server side rendering I get the error:

locals[0] does not appear to be amoduleobject with Hot Module replacement API enabled

Which makes sense since module only exists in a webpack environment. However, I still need it to run for server side rendering...?

{
  "env": {
    "development": {
      "plugins": [
        "react-transform"
      ],
      "extra": {
        "react-transform": [{
          "target": "react-transform-hmr",
          "imports": ["react"],
          "locals": ["module"]
        }, {
          "target": "react-transform-catch-errors",
          "imports": ["react", "redbox-react"]
        }]
      }
    },
    "production": {
      "optional": [
        "optimisation.react.constantElements",
        "optimisation.react.inlineElements"
      ]
    }
  }
}

Unpatched `react-proxy` dependency breaks React Native build

The latest stable release of React Native packager is broken due to the react-transform-hmr's transitive dependency react-deep-force-update including a Babel 6 incompatible .babelrc file in the npm package. (See facebook/react-native#5393)

This dependency is already fixed upstream at [email protected].

In order to fix the issue downstream at React Native, I believe we will need a new release that updates this dependency. I am not deep enough into this library to be able to safely make and test this upgrade. I will submit a PR for convenience, but would appreciate if a maintainer could weigh in.

No hot reloading with componentDidMount as class property

In the context of a class

export default class Frontend extends Component {

With this, hot reloading works:

componentDidMount() {
  this.props.dispatch(whoami());
}

But with this, no hot reloading happens in the component or any of its child components:

componentDidMount = () => {
  this.props.dispatch(whoami());
};

Based on #51, I'd expect that making a change to componentDidMount would not trigger a hot reload when declared as a class property.

What surprises me is that making a change to the render method in the component—which is not a class property—fails to trigger a hot reload.

I'm able to consistently reproduce the problem with this test component:

import React, { Component } from 'react';

export default class TestComponent extends Component {

  componentDidMount = () => {
    console.log("why can't I have nice things?");
  };

  render() {
    return (
      <div>{'change me for hot reloading'}</div>
    );
  }
}

While this component hot reloads as expected:

import React, { Component } from 'react';

export default class TestComponent extends Component {

  render() {
    return (
      <div>{'change me for hot reloading'}</div>
    );
  }
}

Maybe a bug with my setup, or maybe a bug with react-transform-HMR. If it's the former, sorry to waste your time—if the latter, perhaps this helps.

(Thanks so much for your work on this and related components. My team and I have truly enjoyed working with Redux, etc.)

react-transform-hmr is being required in jest tests?

I'm not sure why this might be happening, but I'm getting the following on a new project on the first jest test:

node_modules/react-transform-hmr/lib/index.js: Cannot read property 'type' of null

I was confused why react-transform-hmr was even being required for anything, so I took out the react-transform stuff from babelrc and uninstalled the module, but then I got

product-preview.jsx: Cannot find module 'react-transform-hmr' 

So it seems like it's being explicitly required somewhere/somehow.

Any guidance would be greatly appreciated, thanks so much for the great product!

Page is not being reloaded after update module name from: react-transform-webpack-hmr to react-transform-hmr

The message is:

[HMR] The following modules couldn't be hot updated: (Full reload needed)
processUpdate.js:60 [HMR]  - ./src/components/Blank.jsx
processUpdate.js:91 [HMR] Reloading page

And the page is not being reloaded with the component change :(
It was working well before I made the change on .babelrc, and updating the references of module name

the component is very simple:

import React, { Component, PropTypes } from 'react';
import Form, { Input, Button } from '../../../../core/components/form';
import Panel, { PanelHeading, PanelHeadingTitle, PanelBody, PanelFooter } from '../../../../core/components/Panel'

class Blank extends Component {
    constructor (props, context) {
        super(props, context);

        this.state = {
            canSubmit: false
        };

        this.onValid = this.onValid.bind(this);
        this.onInvalid = this.onInvalid.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onValid () {
        this.setState({
            canSubmit: true
        });
    }

    onInvalid () {
        this.setState({
            canSubmit: false
        });
    }

    onSubmit (model) {
        console.log('model', model);
    }

    render () {
        const {name, unreadCount} = this.state;

        return (
            <Panel color="primary">
                <PanelHeadingTitle>Sample Form</PanelHeadingTitle>
                <Form onSubmit={ this.onSubmit } onValid={ this.onValid } onInvalid={ this.onInvalid }>
                    <PanelBody>
                        <Input name="name" placeholder="Your Name" required>Names</Input>
                        <Input name="lastname" placeholder="Your Last Name">Last Name</Input>
                        <Input name="Username" placeholder="Your Username" icon="user">Username</Input>
                        <Input name="email" icon="envelope" validations="isEmail" validationError="This is not a valid email" placeholder="Your Email" required>Email</Input>
                    </PanelBody>
                    <PanelFooter>
                        <Button type="submit" color="primary" disabled={!this.state.canSubmit}>Submit</Button>
                    </PanelFooter>
                </Form>
            </Panel>
        );
    }
}

export default Blank;

Any suggestion?
Regards.

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.