-
-
Notifications
You must be signed in to change notification settings - Fork 45
Description
最近在移动端使用nginx
反向代理配合webpack-dev-server
和charles
调试时,发现部分手机打不开页面,现象是白屏,或是页面不正常(包括样式等)。
已经排除各种配置的问题。
推断可能是某些代码在老旧机型上不兼容,直接报错,导致程序crash,在入口模板html中插入了一段全局错误捕捉脚本:
window.onerror = function(message) {
alert(message)
}
这里需要注意一点,先监听事件,后续的错误才会触发该事件。
再次进入要调试的页面,弹出SyntaxError: Use of const in strict mode.
错误。
原因:
webpack-dev-server
从2.8.0
版本开始,注入到bundle.js
中js
包含了es6
语法,低版本webview对es6
语法支持有限,兼容性较差,语法报错导致程序crash(白屏和页面不正常的原因),项目使用的版本是2.9.1
。
查看bundle.js
可见如下代码:
/* 2 */
/*!*******************************************************************!*\
!*** multi (webpack)-dev-server/client?http://0.0.0.0:3000 ./app ***!
\*******************************************************************/
/*! dynamic exports provided */
/*! all exports used */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(/*! /Users/elsa/workspace/webpack/webpack2.x+/node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:3000 */3);
module.exports = __webpack_require__(/*! /Users/elsa/workspace/webpack/webpack2.x+/webpack-dev-server/在老旧浏览器报错的问题/app */25);
/***/ }),
这是webpack-dev-server
设置inline:true
时注入到bundle.js
文件中的,通过websocket
通知浏览器进行livereload
,__webpack_require__(3)
这一句去加载node_modules/webpack-dev-server/client/index.js
文件,该文件2.7.1
和2.8.0
的源码如下:
https://github.com/webpack/webpack-dev-server/blob/v2.8.0/client/index.js
https://github.com/webpack/webpack-dev-server/blob/v2.7.1/client/index.js
对比可知,2.8.0
版本开始,该文件使用了es6
的const
和let
语法,__然而,我们开发的时候,使用webpack
编译时,babel-loader
一般都会指定要排除的目录如下:
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
}
}
]
}
所以,babel-loader
并不会将node_modules/webpack-dev-server/client/index.js
转换为es5
的语法。
解决方案:
- 通过降级
webpack-dev-server
到2.7.1
版本 - 测试通过 - 使用
babel-loader
时,在非生产环境配置中,额外指定对node_modules/webpack-dev-server/client/index.js
脚本的转换 - 测试通过
参考链接:
webpack/webpack-dev-server#1105
https://github.com/webpack/webpack-dev-server#caveats