• 3.2.5 webpack代码分离


    为什么需要代码分离?

      为了将代码分成多个bundle,并灵活定制加载策略(按需加载,并行加载),从而大大提升应用的加载速度

    如何代码分离?

      1、入口起点:使用entry配置手动的分离代码

      2、放置重复:使用SplitChunkPlugin去重和分离chunk

      3、动态导入:通过在代码中使用动态加载模块的语法来分离代码

    1、多入口构建

    module.exports = {
        entry: {
         app: "./src/index.js",
         app2: "./sec/anthor-module.js"
        },
        output: {
            path: __dirname + "/src/dist",
            filename: "./[name].bundle.js",
      }
    }

      最终结果:index.bundle.js / another.bundle.js

      问题: 1、公共资源可能被重复引入 2、不够灵活 (两个文件都引入lodash,那最终的bundle中都半酣loadsh,每个bundle都需要我们通过entry配置)

    2、SplitChunks

      曾经有专门的插件去做,在webpack4中将其统一到了optimization配置中,成为了一个官方的优化项

    module.exports = {
      entry: {
       app: "./src/index.js",
       app2: "./sec/anthor-module.js"
      },
      output: {
          path: __dirname + "/src/dist",
          filename: "./[name].bundle.js",
      },
      optimization: {
        splitChunks: {
          chunks: 'all' // 开启 自动的抽取代码 功能
        }
      }
    }

      最终结果:index.bundle.js / another.bundle.js / anther-index.bundle.js(公共依赖),,,splitChunks插件

    3、动态导入

      1. import() 

      2. require.ensure()

    import(
      /**webpackChunkName: "lodash" */ 'lodash'
    )
    .then(({ default: _ }) => {
      // ```
    })
    .catch(error => {
      // error
    })
  • 相关阅读:
    数据库
    HTTP请求(Request)和回应(Response)对象
    [Uliweb]-URL映射
    git生成Key操作保存到GITHUB中
    SQL中char、varchar、nvarchar的区别
    Uliweb之 ORM基本使用(Sqlalchemy)
    ORM查询
    CentOS更改ssh端口
    django static文件的引入方式
    Redis持久化策略(RDB &AOF)
  • 原文地址:https://www.cnblogs.com/slightFly/p/13977132.html
Copyright © 2020-2023  润新知