1. Vite 打包中的 CommonJS 转换机制解析
在 Vite 项目的构建过程中,我们经常会遇到需要处理 CommonJS 模块的情况。虽然 Vite 原生支持 ES 模块,但现实世界中仍存在大量 CommonJS 格式的依赖包。这就是为什么 build.commonjsOptions.include 配置项显得尤为重要。
CommonJS 和 ES 模块的主要区别在于加载机制:
- CommonJS 是动态加载,
require()可以在任意位置调用 - ES 模块是静态的,
import必须位于模块顶层
当 Vite 遇到 CommonJS 模块时,它需要将这些模块转换为 ES 模块格式才能正常工作。这个转换过程由 @rollup/plugin-commonjs 插件完成,而 include 配置就是用来精确控制哪些模块需要被转换的。
2. include 配置的使用场景分析
2.1 默认情况下的自动包含
Vite 的默认配置已经能处理大多数 CommonJS 模块:
javascript复制// vite.config.js
export default {
build: {
commonjsOptions: {
include: [/node_modules/], // 默认包含所有 node_modules
exclude: [] // 默认不排除任何模块
}
}
}
这种配置下,Vite 会尝试转换所有 node_modules 中的 CommonJS 模块。这在大多数情况下都能正常工作,但存在几个特殊场景需要特别注意。
2.2 需要显式配置 include 的典型场景
2.2.1 处理非 node_modules 中的 CommonJS 模块
当项目中有以下情况时,需要手动指定 include:
- 项目自身包含 CommonJS 格式的源代码
- 通过 monorepo 引入的本地 CommonJS 包
- 通过文件路径直接引用的第三方脚本
javascript复制// 示例配置
export default {
build: {
commonjsOptions: {
in
解锁全文
加入我们的会员,获取最新、最热、最精彩的开发者技术内容