3

I'm using webpack/react-starter and I'm trying to test using a mobile device connected to the same LAN as my development machine. So instead of putting in localhost:3000 I put the IP 192.168.X.X:3000 into my mobile browser.

What is the best practice for this since mobile won't know be able to evaluate a script tag with localhost? I put this hacky script in the html that gets served in dev but this feels wrong.

<script>
    //inserts new script tag with localhost replaced by ip
    if('ontouchstart' in window){
        var ipRegex = /([0-9]{3}\.){2}[0-9]{1,3}\.[0-9]{1,3}/;
        var ip = window.location.href.match(ipRegex)[0];
        var url = Array.prototype.shift.call(document.getElementsByTagName('script')).getAttribute('src');
        var newScript = document.createElement('script');
        newScript.src=url.replace('localhost',ip);
        document.body.appendChild(newScript);
    }
</script>

This fetches down the bundle but socket.io can't connect to webpack-dev-server [Error] Failed to load resource: Could not connect to the server. (socket.io, line 0) which won't let me use HMR. What do normal people do in this case?

mbow
  • 147
  • 1
  • 3
  • 11

2 Answers2

3

Other than doing it in the html in a script tag, you could put the IP in the config and it can be replaced into the script url (that pulls down the bundle) before it is even served to the client.

As for the socket.io errors, in the call to webpack-dev-server in package.json you can pass in some flags namely --host and --port. These are used by socket.io for the client side connection url. Specify the IP after --host like this:

webpack-dev-server --config webpack-dev-server.config.js --progress --colors --host 192.168.x.x --port 2992 --inline

Now I can test and get the benefits of hot module reloading on a mobile.

If you're using the webpack-dev-server API instead of CLI, as is the case with steida/este, you'll need to make sure that webpack-dev-server listens to either 0.0.0.0 or your IP address like this:

new WebpackDevServer(webpack(webpackConfig), options).listen(2992, '0.0.0.0', callback);
mbow
  • 147
  • 1
  • 3
  • 11
0

With inline off, webpack/hot/only-dev-server in my entry and this at the bottom of my index.html, it seems to work from anywhere:

<script>
  var devServer = document.createElement('script');
  devServer.setAttribute('src', 'http://' + window.location.host + '/webpack-dev-server.js');
  document.body.appendChild(devServer);
</script>
Aaron Jensen
  • 6,030
  • 1
  • 30
  • 40