如何在Vite热重载时自动运行Prettier与ESLint?
在Vite热重载时自动执行Prettier和ESLint的配置方案
一、Vite内置钩子实现(推荐)
利用Vite的server.watch.onRebuild钩子,在文件变化触发热重载后自动执行格式化和检查脚本,无需依赖VS Code配置。
修改项目根目录的vite.config.js(或.ts):
import { defineConfig } from 'vite'; import { exec } from 'child_process'; export default defineConfig({ server: { watch: { async onRebuild(error) { if (!error) { // 依次执行Prettier格式化与ESLint检查 exec('npm run format', (fmtErr, fmtOut) => { fmtErr ? console.error('Prettier执行失败:', fmtErr) : console.log('Prettier执行完成:', fmtOut); exec('npm run lint', (lintErr, lintOut) => { lintErr ? console.error('ESLint执行失败:', lintErr) : console.log('ESLint执行完成:', lintOut); }); }); } } } } });
注:
child_process是Node.js内置模块,无需额外安装。若需要更可靠的异步处理,可使用util.promisify包装exec方法。
二、VS Code Tasks配置方案
如果偏好通过VS Code控制任务执行,可按以下步骤设置:
- 在项目的
.vscode目录下创建tasks.json(无该目录则新建):
{ "version": "2.0.0", "tasks": [ { "label": "run-lint-format", "type": "shell", "command": "npm run format && npm run lint", "presentation": { "panel": "shared", "reveal": "silent" } }, { "label": "auto-run-lint-format", "type": "shell", "command": "npm run format && npm run lint", "trigger": "onSave", "problemMatcher": [] } ] }
- 开启VS Code保存时自动触发任务:
打开设置(快捷键Ctrl+,),搜索tasks.runOnSave并启用,在include列表中添加任务标签auto-run-lint-format;同时可将files.autoSave设置为afterDelay,确保文件自动保存时触发任务(Vite热重载通常伴随文件保存)。
三、手动执行与Git钩子方案
不少开发者会选择在代码提交前手动执行npm run lint/npm run format,或通过husky+lint-staged配置Git提交钩子,在代码暂存时自动执行检查与格式化。这种方式不会在开发热重载时频繁触发脚本,避免影响开发流畅度,同时能保证提交到仓库的代码符合规范。
内容的提问来源于stack exchange,提问作者msxplus
相关产品推荐
相关产品推荐

