2

我正在使用webpack/react-starter,我试图使用与我的开发机器连接到同一LAN的移动设备进行测试。因此,不要将localhost:3000放入我的移动浏览器中,而是将IP 192.168.X.X:3000。手机上的webpack-dev-server测试

这是什么最佳实践,因为手机不知道能够评估本地主机的脚本标记?我把这个hacky脚本放在开发中的html中,但这种感觉是错误的。

<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> 

此取下来的包,但socket.io无法连接到的WebPack-DEV-服务器[Error] Failed to load resource: Could not connect to the server. (socket.io, line 0),不会让我使用HMR。普通人在这种情况下做什么?

回答

3

除了在脚本标记中的html中执行此操作之外,您可以将IP置于配置中,并且可以在将它提供给客户端之前将其替换到脚本url中(将该包拉下来)。

至于socket.io错误,在调用webpack-dev-server的package.json时,可以传入一些标志,即--host和--port。这些被socket.io用于客户端连接url。指定这样的IP后 - IP:

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

现在我可以测试并获得在移动设备上重新加载热模块的好处。

如果您正在使用的WebPack-DEV-服务器API代替CLI的,如与steida/este的情况下,你需要确保的WebPack-DEV-服务器listen s到任何0.0.0.0或您的IP地址一样这样的:

new WebpackDevServer(webpack(webpackConfig), options).listen(2992, '0.0.0.0', callback); 
0

随着内嵌了,webpack/hot/only-dev-server在我entry,这在我的index.html的底部,它似乎在任何地方工作:

<script> 
    var devServer = document.createElement('script'); 
    devServer.setAttribute('src', 'http://' + window.location.host + '/webpack-dev-server.js'); 
    document.body.appendChild(devServer); 
</script>