zoukankan      html  css  js  c++  java
  • 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
    })
  • 相关阅读:
    Linux的命令技巧
    MAC地址表、ARP缓存表以及路由表
    边缘触发(Edge Trigger)和条件触发(Level Trigger)
    vue-router跳转页面
    正则表达式(简单易懂篇)
    Markdown快速使用指南
    WEB前端资源集(二)
    WEB前端资源集(一)
    js判断移动端与pc端
    js原声快速实现选项卡
  • 原文地址:https://www.cnblogs.com/slightFly/p/13977132.html
Copyright © 2011-2022 走看看