webpack4学习系列(四):code splitting

一、webpack实现code splitting的途径

常用的代码分离方法:

  • 入口起点:使用 entry 配置手动地分离代码。
  • 动态导入:通过模块的内联函数调用来分离代码。

1)入口起点
webpack.config.js

/*代码分离的方式1:通过entry配置分离代码,此时如果入口 chunks 之间包含重复的模块,那些重复模块都会被引入到各个 bundle 中*/
/*此时可以设置optimization,vender防重复*/
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
    mode: 'none',
    entry: {
        index: "./src/category/splitchunk/splitchunk.js",
        another: './src/category/splitchunk/another.js'
    },
    optimization:{
        splitChunks:{
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'common',
                    chunks: 'all'
                }
            }
        }
    },
    plugins: [
        new HTMLWebpackPlugin({
            title: 'Code Splitting'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve('./dist')
    }
};

正如前面提到的,这种方法存在一些问题:

如果入口 chunks 之间包含重复的模块,那些重复模块都会被引入到各个 bundle 中。
这种方法不够灵活,并且不能将核心应用程序逻辑进行动态拆分代码。

为了解决重复引入的问题,这里我们设置了optimization.splitChunks,将 lodash 分离到单独的 chunk。打包后的效果如图


image.png

2)动态导入
1⃣️使用符合 ECMAScript 提案import() 语法

这里的import不同于模块引入时的import,可以理解为一个动态加载的模块的函数(function-like),传入其中的参数就是相应的模块。例如对于原有的模块引入

import react from 'react'

可以写为

import('react')

但是需要注意的是,import()会返回一个Promise对象

import() 调用会在内部用到 promises。如果在旧有版本浏览器中使用 import(),记得使用 一个 polyfill 库(例如 babel-polyfill)

index.js

import "babel-polyfill";

async function getComponent() {
    var element = document.createElement('div');
    const _ = await import(/* webpackChunkName: "lodash" */ 'lodash');
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    return element;
}

getComponent().then(component =>{
    document.body.appendChild(component);
});

由于 import() 会返回一个 promise,因此它可以和 async 函数一起使用。但是,需要使用像 Babel 这样的预处理器和Syntax Dynamic Import Babel Plugin

webpack.config.js

/*代码分离的方式2:动态导入*/
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

/* 一款分析 bundle 内容的插件及 CLI 工具,以便捷的、交互式、可缩放的树状图形式展现给用户。 */
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
    mode: 'none',
    entry: {
        index: "./src/category/splitchunk/splitchunk.js"
    },
    plugins: [
        new HTMLWebpackPlugin({
            title: 'Code Splitting'
        }),
        new BundleAnalyzerPlugin() 
    ],
    output: {
        filename: '[name].bundle.js',
        chunkFilename:'[name].bundle.js',
        path: path.resolve('./dist')
    },
    module:{
        rules:[
            {
                test:/(\.jsx|\.js)$/,
                use:{loader:"babel-loader"},
                exclude:/node_modules/
            }
        ]
    }
};

.babelrc

{
  "presets": [
    ["@babel/preset-env"],
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-syntax-dynamic-import"
  ]
}

打包后的效果


image.png

2⃣️require.ensure()

require.ensure() is specific to webpack and superseded by import().

推荐用import取代

二、react-router v4 中的代码拆分

常规写法

'use strict';
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';

import OrderPage from './orderpage';
import Home from './home';

class APP extends Component {
    render() {
        return (
            <Switch>
                <Route exact path="/" component={Home} />
                <Route exact path="/OrderPage" component={OrderPage} />
                <Route component={Home} />
            </Switch>
        );
    }
}
export default  APP;

进入页面加载的资源如图


image.png

按需加载的写法
我们首先需要一个异步加载的包装组件Bundle。Bundle的主要功能就是接收一个组件异步加载的方法,并返回相应的react组件:

/* 异步加载的包装组件Bundle ,Bundle的主要功能就是接收一个组件异步加载的方法,并返回相应的react组件*/
import React, {Component} from 'react';

export default class Bundle extends Component {
    constructor(props){
        super(props);
        this.state={
            mod  : null
        }
    }
    componentWillMount() {
        this.load(this.props)
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.load !== this.props.load) {
          this.load(nextProps)
        }
    }
    load(props) {
        this.setState({
          mod: null
        });
        props.load().then((mod) => {
            this.setState({
              mod: mod.default ? mod.default : mod
            });
          });
    }
    render() {
        return this.state.mod ? this.props.children(this.state.mod) : null;
    }
}

router.js

'use strict';
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Bundle from './bundle'

const Home = (props)=>(
  <Bundle load={() => import('./home')}>
    {(Home) => <Home {...props}/>}
  </Bundle>
)
const OrderPage = (props)=>(
    <Bundle load={() => import('./orderpage')}>
      {(OrderPage) => <OrderPage {...props}/>}
    </Bundle>
)

class APP extends Component {
    render() {
        return (
            <Switch>
                <Route exact path="/" component={Home} />
                <Route exact path="/OrderPage" component={OrderPage} />
                <Route component={Home} />
            </Switch>
        );
    }
}
export default  APP;

此时,可以看到在载入最初的页面时加载的资源如下


image.png

初始动态加载了0.js这个js文件,如果打开这个文件查看,就可以发现这个就是我们刚才动态import()进来的home.js模块。


image.png

点击跳转到/OrderPage路径时会动态加载1.js文件,该文件就是动态加载进来的orderpage模块
image.png

三、组件库的按需加载

  1. 依赖babel-plugin-import插件
npm install babel-plugin-import --save-dev

使用方式:通过 .babelrc 配置文件引入

"plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-syntax-dynamic-import",
    ["import", { "libraryName": "antd", "libraryDirectory": "lib", "camel2DashComponentName": true }]
  ]

此外,同时设置多个模块的按需加载可按下述方式

"plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-syntax-dynamic-import",
    ["import", { "libraryName": "antd", "libraryDirectory": "lib", "camel2DashComponentName": true },"ant"],
    ["import",{"libraryName":"antd-mobile","libraryDirectory": "lib","camel2DashComponentName": false},"antd-mobile"]
  ]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。