React 开发减少bundle.js体积 减少代码重复引用

本文探讨如何在React开发中通过独立打包每个页面和路由权限配置来减小bundle.js体积,提高页面加载速度。同时,利用工具检查并避免代码块重复引用,以进一步优化应用性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

router配置:

将每个页面单独打包,减少每个js的体积,并行下载,加快页面加载速度。

  const routes = {
    path: `${config.contextRoot}/`,
    indexRoute: {
      name: '首页',
      component: Home
    },
    childRoutes: [
      {
        path: 'app',
        getComponent: (location, cb) => {
          require.ensure([], () => {
            cb(null, require('./containers/MainFrame').default);
          }, 'MainFrame');
        },
        childRoutes: [
          {
            path: 'register',
            name: '注册',
            getComponent: (location, cb) => {
              // './containers/investment/protocol'为公共代码块,提取出来,避免重复打包
              require.ensure(['./containers/investment/protocol'], () => {
                cb(null, require('./containers/Register').default);
              }, 'Register');
            },
            onEnter: noLogin
          }
        ]
      }
    ]
  };

路由权限配置:

  // 用户必须先登录 
  const requireLogin = (nextState, replaceState, cb) => {
    const { application: { user } } = store.getState();
    if (!user) {
      replaceState({
        nextPathname: nextState.location.pathname
      }, '/app/login');
    }
    cb();
  };

  // 用户不能为登录状态 
  const noLogin = (nextState, replaceState, cb) => {
    const { application: { user } } = store.getState();
    if (user) {
      replaceState({
        nextPathname: nextState.location.pathname
      }, '/');
    }
    cb();
  };

对于重复的代码块,需要在router里面独立出来,在package.json.js里面单独配置

entry: {
    'protocol': ['./src/web/containers/investment/protocol.js']
  },
new webpack.optimize.CommonsChunkPlugin({
        name: ['protocol'],
        minChunks: Infinity
    })

检查代码块重复引用部分

网址:https://webpack.github.io/analyse/

webpack打包

webpack --profile --json > stats.json

上传文件页面

重复代码块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值