Correct incremental build for Vite: content hashing, dependency graph, parent invalidation.
Projects that need to be built to disk instead of being served by the Vite dev server. If you can, the recommended approach is to use CSP to allow localhost in dev and use the Vite dev server without this plugin.
npm i -D vite-incra tsximport { defineConfig } from 'vite'
import { incrementalBuild } from 'vite-incra'
export default defineConfig({
plugins: [
// ... your other plugins (react, vue, etc.)
incrementalBuild({
bundleName: 'bundle',
watcherIgnoredFiles: [/node_modules/, /\.git/, /dist/],
beforeBuildCallback: () => {
/* runs before each build */
},
cleanBeforeFirstBuild: true,
watch: true,
watcherUsePolling: true,
}),
],
root: '.',
build: {
outDir: 'dist',
emptyOutDir: true,
},
}){
"scripts": {
"build": "vite build",
"build:incremental": "vite-incra"
}
}npm run build:incrementalOr without adding a script:
npx vite-incra- Watch mode (default): Watches
src/,public/,index.htmland rebuilds only when files change. - Single run: Pass
watch: falseto the plugin if you run from CI and want one build then exit. - Force build: With
watch: false, usevite-incra --forceto build even when no changes are detected.
project/
├── index.html
├── package.json
├── vite.config.ts
├── src/
│ ├── main.tsx # or main.ts, main.js
│ └── ...
├── public/
│ └── ...
└── dist/ # output
vite.configmust haverootset- If you set
build.rollupOptions.input, it must be an object (e.g.{ main: 'index.html' }), not a string or array
For custom scripts (e.g. tools/incrementalBuild.ts):
import { runIncrementalBuild, patchConfig } from 'vite-incra'
import viteConfig from '../vite.config'
runIncrementalBuild(patchConfig(viteConfig), {
watch: false,
force: true, // build even when no changes detected
bundleName: 'bundle',
watcherIgnoredFiles: [/node_modules/, /\.git/],
beforeBuildCallback: () => {
/* ... */
},
})Requires tsx for running TypeScript:
npm i -D vite-incra tsx- Extensions: Don't use this package. Build minimal files for install, serve JS from Vite dev server, allow localhost in CSP.
- File remapping: Use Vite middleware for build path remapping.
- Tested: React (TypeScript + JavaScript).
- Build speed: Depends on how many files the changed file imports. More imports = longer incremental build.
Inspired by momentumdash/vite-plugin-incremental-build.