Skip to content

Instantly share code, notes, and snippets.

@esamattis
Last active May 19, 2019 00:36
Show Gist options
  • Save esamattis/28c2dbcbe8109a0c5edb to your computer and use it in GitHub Desktop.
Save esamattis/28c2dbcbe8109a0c5edb to your computer and use it in GitHub Desktop.
React hot reloading with Webpack for Ruby on Rails
<script charset="utf-8">
<% if ENV["RAILS_ENV"] == "production" %>
var script = "/react-app-bundle.js";
<% else %>
console.warn("Development mode. Make sure to start 'node devServer.js'");
var script = "http://" + (location.host || 'localhost').split(':')[0] + ":4000/react-app-bundle.js"
<% end %>
document.write('<script src="' + script + '"></' + 'script>');
</script>
var path = require("path");
var express = require("express");
var webpack = require("webpack");
var config = require("./webpack.config");
var app = express();
var compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
}));
app.use(require("webpack-hot-middleware")(compiler));
app.listen(4000, "0.0.0.0", function(err) {
if (err) {
console.log(err);
return;
}
console.log("Listening at http://0.0.0.0:4000");
});
var webpack = require("webpack");
// This must be the public address where the hot reload bundle is loaded in the
// browser. Yeah it sucks to hard code it here. Let's hope for the better
// future
var PUBLIC_DEV_SERVER = "http://my-dev-server:4000/";
var ENTRY = "./index.js";
var NODE_ENV_PLUGIN = new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
});
var config = {
entry: [
"webpack-hot-middleware/client?path=" + PUBLIC_DEV_SERVER + "__webpack_hmr",
ENTRY
],
output: {
path: __dirname + "/public",
filename: "react-app-bundle.js",
publicPath: PUBLIC_DEV_SERVER
},
devtool: "cheap-module-eval-source-map",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel",
query: {
"env": {
// Not active when NODE_ENV=production
"development": {
"plugins": ["react-transform"],
"extra": {
"react-transform": [{
"target": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}
}
}
}
}
]
},
plugins: [
NODE_ENV_PLUGIN,
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
]
};
// Drop all hot stuff for production!
if (process.env.NODE_ENV === "production") {
config.devtool = "source-map";
config.entry = ENTRY;
delete config.output.publicPath;
config.plugins = [NODE_ENV_PLUGIN];
}
module.exports = config;
@praweb
Copy link

praweb commented Apr 21, 2017

Tried the same setup.. but end up with "EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection." error. Any idea about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment