Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dva中组件的懒加载 #9

Closed
javanli opened this issue Jul 6, 2020 · 0 comments
Closed

dva中组件的懒加载 #9

javanli opened this issue Jul 6, 2020 · 0 comments

Comments

@javanli
Copy link
Owner

javanli commented Jul 6, 2020

组件的按需加载是提升首屏性能的重要手段。

[email protected]使用了[email protected],相关的使用方式有变化,网上的讨论基本上都是旧的,不清楚的话会比较乱,这里做一下记录。

[email protected]以前

[email protected]以前的懒加载相关讨论有不少,可以参考dva-example-user-dashboard中的写法,徐飞大佬的文章使用 Dva 开发复杂 SPA,本质上借助的是webpack的require.ensure实现代码分割,参考代码分割 - 使用 require.ensure
具体实现形如:

function RouterConfig({ history, app }) {
  const routes = [
    {
      path: '/',
      name: 'IndexPage',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          registerModel(app, require('./models/dashboard'));
          cb(null, require('./routes/IndexPage'));
        });
      },
    },
    {
      path: '/users',
      name: 'UsersPage',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          registerModel(app, require('./models/users'));
          cb(null, require('./routes/Users'));
        });
      },
    },
  ];

  return <Router history={history} routes={routes} />;
}

[email protected]以后

[email protected]使用了[email protected],其中的路由是组件式的,原来的方式就不太好搞。因此dva提供了一个dynamic函数来处理。
[email protected]发布日志dva api文档中有介绍。
具体实现形如:

import dynamic from 'dva/dynamic';

function RouterConfig({ history,app }) {
  const UserPageComponent = dynamic({
    app,
    models: () => [
      import('./models/users'),
    ],
    component: () => import('./routes/UserPage'),
  });
  return (
    <Router history={history}>
      <Switch>
        <Route path="/user" component={UserPageComponent} />
        <Route component={IndexPageComponent} />
      </Switch>
    </Router>
  );
}
export default RouterConfig;
@javanli javanli closed this as completed Sep 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant