如何通过代码拆分多次阻止供应商加载

时间:2017-06-07 20:41:34

标签: webpack create-react-app

我现在正在玩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;

所以HomePageAboutPage目前基本相同,但它只是一个游乐场。

问题是:HomePageAboutPage的块加载了整个styled-components包。这应该加载一次,不应该加载吗?

enter image description here

正如您在图片中看到的那样,2.chunk.js1.chunk.js均为121kb。我认为一旦包被多次导入,代码拆分会将styled-components移动到它自己的块中?

要获取您的信息:我使用的是create-react-app且未运行eject,因此我不知道webpack配置中的内容(如果这应该很重要。)

1 个答案:

答案 0 :(得分:3)

问题是缺少webpackRequireWeakId

而不是......

const HomePage = RouteLoader({ loader: () => import('routes/home') })

......我必须使用......

const HomePage = RouteLoader({ 
  loader: () => import('routes/home'),
  webpackRequireWeakId: () => require.resolveWeak('routes/home')
})

...如react-loadablehttps://github.com/thejameskyle/react-loadable#why-are-there-multiple-options-for-specifying-a-component

的文档中所述