webpack core

2021/06/15 Webpack 共 864 字,约 3 分钟

前端为什么需要打包器

  • 不是所有的浏览器都直接支持JS规范(最新/所有特性)
  • 脚本之间的依赖关系、加载顺序需要管控
    • 传统脚本加载处理方式:
      • 每个脚本存放单独的功能
        • 脚本太多,加载浪费并发请求数,性能差
        • 脚本之间依赖关系不清晰
        • 脚本污染全局作用域
      • 单独一个脚本存放所有功能
        • 维护困难、可读性差
        • 作用域难以管理

webpack

工作原理

了解loaderplugin工作时机之前,我们首先需要知道webpack工作原理:

  • webpack通过entry入口索引机制,进行依赖解析检索
    • 我们所有的依赖都是一个个可以被webpack解析的module模块
  • 对每个module进行loader匹配处理
    • 主要注意同reg(eg: test: /\.jsx?$/)规则声明下,loader从后向前解析
    • 最开始的loader接收source,后面的每个loader接收前面loader的返回值
  • 所有loader合并为chunk,在这个阶段,plugin可以介入进行enhance处理
  • chunk经过plugin处理/拆分,生成bundle
    • bundle即最终能被浏览器识别的最终文件

Loaders and Plugins 工作时机

Loaders

  • Loaders work at the individual file(module) level during or before the bundle is generated.

Plugins:

  • Plugins work at bundle or chunk level and usually work at the end of the bundle generation process.
  • Plugins can also modify how the bundles themselves are created.
  • Plugins have more powerful control than loaders.

二者工作时机可以参考下图:

loaders and plugins work time

实现一个loader

实现一个plugin


[1] webpack-loaders-vs-plugins-whats-the-difference

[2] hash-chunkhash-contenthash

Search

    Table of Contents