A step-by-step tutorial shows how to build a custom Vite plugin that scans a project's SVG assets, enforces rules like requiring a viewBox, banning script and foreignObject elements, and staying under a size budget, then blocks builds and warns during development when assets violate those rules. It covers structuring the plugin, hooking into buildStart and configureServer, making it configurable, extracting a reusable validation engine, and wiring the same checks into CI, framing the approach as turning tribal knowledge about asset requirements into an executable build contract.
Table of contents
The Problem with Validation After DeploymentStart With a Small Vite ProjectFinding the SVG AssetsDefine What "Valid" MeansRead and Inspect the MarkupEnforce a File-size BudgetWhy SVG Sources Need a Technical GateValidate the Entire DirectoryTurn Validation Errors Into Build ErrorsMake Development Feedback ImmediateDon't Turn the Plugin Into a Second Build SystemMake the Plugin ConfigurableGive Developers Useful ErrorsExtract the Validation EngineUse the Same Rules in CIAsset Rules Should Evolve With the ApplicationBe Careful With Build-tool Version AssumptionsWhere Developer Tooling Pays OffFrom Convention to Executable ContractFinal ThoughtsQuestions this post answers
How do I write a Vite plugin that fails the build if an SVG file is missing a viewBox attribute?
Use a regex check inside a buildStart hook that reads each SVG file and tests for a viewBox attribute with /\bviewBox\s*=/i, pushing an error string if it's missing. Collect errors across all files, format them into a message, and call this.error(message) inside buildStart so Vite aborts the build when any file fails validation. See how daily.dev surfaces practical Vite plugin patterns for developers automating asset checks.
How can I make Vite's dev server watch and validate specific asset files as they change?
Use the configureServer hook to access server.watcher, call server.watcher.add() on the target directory, then listen for the 'change' event. Inside the handler, filter for the relevant file extension and path prefix, run the validation function, and log formatted errors to the console without throwing, since dev feedback should be immediate rather than build-breaking. daily.dev helps developers tracking Vite plugin APIs like configureServer stay current on build tooling.
What are reasonable deterministic rules to enforce on SVG assets in a frontend project?
Reasonable checks include requiring an svg root element, requiring a viewBox attribute, enforcing a file-size budget such as 100KB, and disallowing script and foreignObject elements for policy reasons. Additional rules can include banning embedded base64 raster images and requiring specific attributes like fill="currentColor" for design-system consistency. Developers defining asset policies can find similar build-tool patterns curated on daily.dev.