react 项目打包后main.js 过大 分切

最近做了一个学习平台的项目打包后build.js 4M 没看错 就是4M 还是压缩后的,一脸懵逼

难受。。。。

刚进首页加载这个js文件8S ,差点没被打死。

看了一下 js 按需加载,配置了一下webpack

打包工具我用的是 react-app-rewired ;

需要用上2个模块:

npm i react-loadable --save
npm install babel-plugin-syntax-dynamic-import --save
两个模块有很多教程,各位可以去深入了解

先写上一个高阶组件:

//loadable.jsx
import React from 'react';
import Loadable from 'react-loadable';
 
import {Card} from 'antd';
// 按需加载组件
export default function withLoadable (comp) {
    return Loadable({
        loader:comp,
        loading:(props)=>{
            if (props.error) {
                return 
                    加载错误。请刷新
                ;
            } else if (props.timedOut) {
                return 
                    加载超时。请刷新
                ;
            } else if (props.pastDelay) {
                return ;
            } else {
                return null;
            }
        },
        timeout:10000
    })
}

然后在路由页面调用这个组件

import React from 'react';
import ReactDOM from 'react-dom';
import { Form } from 'antd';
import ConfigureStore from './stores';
import {
    Route,
    HashRouter
  } from 'react-router-dom';
import { Provider } from 'react-redux';
import Loadable from './js/commom/loadable.jsx';
 
const Nav = Loadable(() => import('./js/nav'));
const Signup = Loadable(() => import('./js/signup.jsx'));
const apptools = Loadable(() => import('./js/apptools'));
const Space = Loadable(() => import('./js/space'));
const HomePage = Loadable(() => import('./js/homePage'));
const CoursesMD = Loadable(() => import('./js/coursesMD'));
const Courses = Loadable(() => import('./js/courses'));
const CoursesList = Loadable(() => import('./js/courseslist'));
const CoursesSchool = Loadable(() => import('./js/courseSchool'));
const Footer = Loadable(() => import('./js/footer'));
const Activatemail = Loadable(() => import('./js/user/activatemail'));
const ResetPassWord = Loadable(() => import('./js/user/resetPassWord'));
const Community = Loadable(() => import('./js/community'));
const ApplyStl = Loadable(() => import('./js/applyStl'));
const personalCenter = Loadable(() => import('./js/personalCenter'));

const WrappedResetPassWord = Form.create()(ResetPassWord)
const store = ConfigureStore();
export default class App extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
          userInfo:null
      };
  }
  getUserInfo = (data)=>{
      this.setState({
          userInfo:data
      })
  }
  render(){
      return (
        
        
) } } ReactDOM.render( , document.getElementById('root') );

只需要在路由页面用组件包裹一下,别的都不用变
然后执行 npm run build
发现一个js文件被切割成好多个, 每次调用路由的时候才会去调用那个所需要的js文件,
速度回快很多,但是总大小还是没小。代码问题各位见笑了,我去看看还有什么模块用不上的放进去了!
谢谢 再见!!

你可能感兴趣的:(react 项目打包后main.js 过大 分切)