很多业务的前端页面开发是用直接代理开发环境的js静态资源到本地资源的方式。静态资源通过代理简单配置即可代理到本地,但是WebSocket代理不一定能成功
通过查看react-scripts包中webpackDevServer的配置
可以通过设置环境变量配置WebSocket的地址,修改package.json中scripts如下
代码语言:javascript复制"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",根大括号增加
代码语言:javascript复制"resolutions": {
"react-error-overlay": "6.0.9"
}
然后安装依赖
重启webpack,刷新页面,修改业务代码
push的更新信息,还是开发环境的地址,我们在react-app-rewired的配置文件config-overrides.js中添加
代码语言:javascript复制if (process.env.NODE_ENV === 'development') {
newConfig.output.publicPath = `http://localhost:${process.env.PORT}/`;
}
设置资源基础路径为本地服务地址
重启webpack,刷新页面,修改业务代码
跨域的错误,在config-overrides.js中配置
代码语言:javascript复制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
有了热更新,大家一定可以早半个小时下班 ^_^