使用react-hot-loader的一些问题

本文探讨了在使用React热更新时遇到的与mini-css-extract-plugin及react-loadable的兼容性问题,并提供了解决方案。建议在开发环境中调整CSS处理方式,避免提取CSS,同时介绍了如何通过hack或弃用AppContainer来解决与react-loadable的冲突。

1.与"mini-css-extract-plugin"插件不兼容

这个官方文档也有提到过,在开发环境中,当使用react-hot-loader时,最好还是不要把css文件提取出来,仍然和js放在一起。

具体方法是在不同的环境配置不同的loader

{
  test: /\.css$/, 
  use: [
    env === "development" ? 'style-loader' : MiniCssExtractPlugin.loader,
    'css-loader'
  ]
},
{
  test: /\.less$/,
  use: [
    env === "development" ? 'style-loader' : MiniCssExtractPlugin.loader,
    'css-loader',
    'less-loader'
  ]
}

  

2.与react-loadable不兼容

当使用react-loadable 按照路由拆分代码的时候,在dev环境热更新不生效。它与react-hot-loader不可以完全兼容,这个问题一直存在,在react-hot-loaderr的 issue 中也有提到过这个问题。

开发这个的一个俄罗斯开发者有提出 react-hot-component-loader 这个工具去hack这些。尝试了很多方法,各种奇怪问题,最后弃用了AppContainer,用hot(module) 强制更新

import React, { Component } from 'react'
import { hot } from 'react-hot-loader'
import { Route, Switch } from 'react-router-dom'
import routes from './router'

class App extends Component {
  render() {
    const routeWithSubRoutes = (route, index) =>
      <Route
        key={index}
        exact={route.exact || false}
        path={route.path}
        render={props => <route.component {...props} routes={route.routes} />}
      />
    return (
      <Switch>
        {routes.map((route, index) => routeWithSubRoutes(route, index))}
      </Switch>
    )
  }
}

export default hot(module)(App)

  

另外我自己用webpack4+react16 搭了一个简单的CSR 渲染脚手架

地址:https://github.com/lyxverycool/react-csr-templete

 

转载于:https://www.cnblogs.com/lyxverycool/articles/11022388.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值