美文网首页
create-react-app 打包优化、首屏优化

create-react-app 打包优化、首屏优化

作者: 初心不改_0055 | 来源:发表于2019-03-18 14:50 被阅读0次

1、antd按需加载

2、将开发环境改为生产环境(原build文件31.7M,修改后build文件为4.3M)
将webpack.config.js中的 devtool 设置为 false

image.png
在使用react-create-app搭建的项目,在我们编译打包时会产生很多.map文件,导致编译后的项目非常大,这个配置就是让打包后的文件不包含.map文件

3、使用动态路由,需要时再加载(首屏加载2s,优化至1s)

创建一个component函数 (目的就是为了将router的component实现异步加载。)

// 异步按需加载component
function asyncComponent(getComponent) {
    return class AsyncComponent extends React.Component {
        static Component = null;
        state = { Component: AsyncComponent.Component };

        componentDidMount() {
            if (!this.state.Component) {
                getComponent().then(({default: Component}) => {
                    AsyncComponent.Component = Component
                    this.setState({ Component })
                })
            }
        }
        //组件将被卸载
        componentWillUnmount(){
            //重写组件的setState方法,直接返回空
            this.setState = (state,callback)=>{
                return;
            };
        }
        render() {
            const { Component } = this.state
            if (Component) {
                return <Component {...this.props} />
            }
            return null
        }
    }
}
function load(component) {
    return import(`${component}`)
}

将已知地址路径传递到一个函数并把这个函数作为参数传递到 asyncComponent中这样asyncComponent就能接收到这个路由的地址了,然后我们要做的就是将这个asyncComponent函数带入到router中。

<Router history={history}>
            <Route exact path="/" when="always" component={App}/>
            <Route exact path="/detail" component={asyncComponent(() => load('./module/Detail'))}/>
            <Route exact path="/detail/processingLog" component={asyncComponent(() => load('./module/earlyWarning/ProcessingLog'))}/>
        </Router>

从代码中可以看出已经实现了router 的component 的引入,这样自然就可以通过一个循环来实现动态的加载啦!

更多优化

相关文章

网友评论

      本文标题:create-react-app 打包优化、首屏优化

      本文链接:https://www.haomeiwen.com/subject/mzvvmqtx.html