如何将被include的Pug文件加入Vite module graph实现热更新?
解决方案
Vite 官方提供了标准适配方案,不需要手动操作 server.moduleGraph,核心是利用 Rollup 兼容的 addWatchFile API 关联 Pug 的隐式依赖,具体实现如下:
实现步骤
Pug 编译接口会返回所有 include/extends 依赖的文件路径,你只需要在编译时把这些路径添加到 Vite 的监听列表即可,修改后的插件代码:
// Rollup plugin imported to Vite config import { compile } from 'pug'; export default function pug() { return { name: 'rollup-plugin-pug-html', transform(src, id) { if (id.endsWith('.pug')) { // 编译Pug同时获取依赖列表 const compileFn = compile(src, { filename: id, // 开启后会把所有include/extends的绝对路径写入compileFn.dependencies compileDebug: process.env.NODE_ENV === 'development' }); const html = compileFn(); // 给当前Pug文件添加所有依赖的监听 if (compileFn.dependencies) { compileFn.dependencies.forEach(depPath => { this.addWatchFile(depPath); }); } const code = `export default ${JSON.stringify(html)};`; return { code }; } }, }; }
生效逻辑
完成修改后,所有被引入的 Pug 依赖文件变更时,Vite 会自动触发依赖它的父 Pug 文件重新编译,后续 HMR 流程和直接修改主 Pug 文件完全一致,组件响应式状态会正常保留。
内容的提问来源于stack exchange,提问作者Rafi
相关产品推荐
相关产品推荐

