我现在正在玩create-react-app和代码分割.在我开始导入供应商库之前,它工作得非常好,这些库将包含在每个块中.
这是我目前的做法:
App.js
const HomePage = Loadable({ loader: () => import('./Home.js'),LoadingComponent: Loading }); const AboutPage = Loadable({ loader: () => import('./About.js'),LoadingComponent: Loading }); class App extends PureComponent { render() { return ( <Router> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> </ul> <hr/> <Route exact path="/" component={HomePage}/> <Route path="/about" component={AboutPage}/> </div> </Router> ); } }
About.js
import React,{ PureComponent } from 'react'; import styled from 'styled-components'; const Button = styled.button` color: aqua; `; class AboutPage extends PureComponent { render() { return ( <div> About <Button>Fooobar!</Button> </div> ); } } export default AboutPage;
Home.js
import React,{ PureComponent } from 'react'; import styled from 'styled-components'; const Button = styled.button` color: orange; `; class HomePage extends PureComponent { render() { return ( <div> Home <Button>Fooobar!</Button> </div> ); } } export default HomePage;
所以HomePage和AboutPage目前基本相同,但它只是一个游乐场.
问题是:HomePage和AboutPage的块加载整个样式组件包.这应该加载一次,不应该吗?
正如您在图像上看到的那样,2.chunk.js和1.chunk.js都是121kb.我认为一旦包被多次导入,代码拆分会将样式组件移动到它自己的块中?
为了您的信息:我正在使用create-react-app并且没有运行弹出,因此我不知道webpack配置中的内容(如果这很重要).
问题是缺少webpackRequireWeakId.
代替 …
const HomePage = RouteLoader({ loader: () => import('routes/home') })
……我必须用……
const HomePage = RouteLoader({ loader: () => import('routes/home'),webpackRequireWeakId: () => require.resolveWeak('routes/home') })
…如react-loadedable:https://github.com/thejameskyle/react-loadable#why-are-there-multiple-options-for-specifying-a-component的文档中所述