解决线上域名Webpack热更新失败问题

很多业务的前端页面开发是用直接代理开发环境的js静态资源到本地资源的方式。静态资源通过代理简单配置即可代理到本地,但是WebSocket代理不一定能成功

通过查看react-scripts包中webpackDevServer的配置

可以通过设置环境变量配置WebSocket的地址,修改package.json中scripts如下

"start": "cross-env DISABLE_ESLINT_PLUGIN=true PORT=3009 WDS_SOCKET_HOST=localhost WDS_SOCKET_PORT=3009 NODE_ENV=development react-app-rewired start",

WebSocket连接到本地后,又出现如下错误

查了资料是react-scripts依赖的react-error-overlay版本过高的问题,需要限制到6.0.9版本。修改package.json,在devDependencies增加"react-error-overlay": "6.0.9",根大括号增加

"resolutions": {
    "react-error-overlay": "6.0.9"
}

然后安装依赖

重启webpack,刷新页面,修改业务代码

push的更新信息,还是开发环境的地址,我们在react-app-rewired的配置文件config-overrides.js中添加

if (process.env.NODE_ENV === 'development') {
  newConfig.output.publicPath = `http://localhost:${process.env.PORT}/`;
}

设置资源基础路径为本地服务地址

重启webpack,刷新页面,修改业务代码

跨域的错误,在config-overrides.js中配置

devServer: function(configFunction) {
  // Return the replacement function for create-react-app to use to generate the Webpack
  // Development Server config. "configFunction" is the function that would normally have
  // been used to generate the Webpack Development server config - you can use it to create
  // a starting configuration to then modify instead of having to create a config from scratch.
  return function(proxy, allowedHost) {
    // Create the default config by calling configFunction with the proxy/allowedHost parameters
    const config = configFunction(proxy, allowedHost);

    config.headers = {
      "Access-Control-Allow-Credentials": "true",
      'Access-Control-Allow-Origin': '*',
    };

    // Return your customised Webpack Development Server config.
    return config;
  };
},

重启webpack,刷新页面,修改业务代码

热更新能力恢复正常!

最后总结一下配置清单

1. 配置WebSocket地址到本地
2. 限制依赖react-error-overlay版本
3. 设置webpack配置output.publicPath为本地服务地址
4. 配置DevServer允许跨域headers

有了热更新,大家一定可以早半个小时下班 ^_^

本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
解决线上域名Webpack热更新失败问题
很多业务的前端页面开发是用直接代理开发环境的js静态资源到本地资源的方式。静态资源通过代理简单配置即可代理到本地,但是WebSocket代理不一定能成功
<<上一篇
下一篇>>