前端为什么需要打包器
- 不是所有的浏览器都直接支持JS规范(最新/所有特性)
- 脚本之间的依赖关系、加载顺序需要管控
- 传统脚本加载处理方式:
- 每个脚本存放单独的功能
- 脚本太多,加载浪费并发请求数,性能差
- 脚本之间依赖关系不清晰
- 脚本污染全局作用域
- 单独一个脚本存放所有功能
- 维护困难、可读性差
- 作用域难以管理
- 每个脚本存放单独的功能
- 传统脚本加载处理方式:
webpack
工作原理
了解loader和plugin工作时机之前,我们首先需要知道webpack工作原理:
webpack通过entry入口索引机制,进行依赖解析检索- 我们所有的依赖都是一个个可以被
webpack解析的module模块
- 我们所有的依赖都是一个个可以被
- 对每个
module进行loader匹配处理- 主要注意同reg(eg:
test: /\.jsx?$/)规则声明下,loader从后向前解析 - 最开始的
loader接收source,后面的每个loader接收前面loader的返回值
- 主要注意同reg(eg:
- 所有loader合并为
chunk,在这个阶段,plugin可以介入进行enhance处理 chunk经过plugin处理/拆分,生成bundlebundle即最终能被浏览器识别的最终文件
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.
二者工作时机可以参考下图: