We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

A User Guide For The Craft CMS Vite Plugin

10 min read
The Craft CMS Vite Plugin

Sick of sluggish frontend build tools hampering your Craft CMS plugin development workflow? Vite provides lightning fast performance and optimized development capabilities tailored for modern web projects. This guide explores everything from installing Vite for Craft CMS to leveraging its speedy HMR and asset handling features. Unlock a blazing fast frontend experience that boosts productivity when building Craft CMS sites.

The Craft CMS Vite plugin provides lightning fast performance and optimized development capabilities for modern web projects. By leveraging native ESM and pre-bundling dependencies, it enables near instantaneous start times, surgical hot module replacement, automatic code splitting, and streamlined asset handling. Migrating from Webpack unlocks huge productivity wins.

Prerequisites for Using the Plugin

PHP Version Needed

To utilise the Craft CMS Vite plugin, your server will need to be running PHP 7.4 or higher. This requirement ensures compatibility with the latest PHP features and syntax that the plugin leverages.

While older versions of PHP may technically work, you'll likely encounter errors during installation or unexpected behaviour while using the plugin. Sticking to PHP 7.4 and above provides a stable foundation.

Some key advantages of PHP 7.4 that the Vite plugin capitalises on include:

  • Improved type declarations for stronger parameter and return type checks.

  • Null coalescing assignment operator for concise default values.

  • Typed properties to indicate expected variable types.

  • Arrow functions for cleaner anonymous functions.


So for a smooth and optimised experience, check your server meets the minimum PHP version prerequisite before installing the plugin. While migrations can feel tedious, upgrading provides long-term benefits that outweigh any short-term hassle.

Required Craft CMS Version

Craft CMS requirements – To unleash the capabilities of the Vite plugin, you'll need to be running Craft CMS 3.4.0 or later. This version requirement ensures full compatibility with the plugin's features and framework.

While it may be possible to install the plugin on earlier versions of Craft, you'll likely encounter odd bugs and limited functionality. The plugin leverages improvements and optimisations introduced in Craft 3.4.0 like:

  • Asynchronous queue jobs for handling resource-intensive tasks.

  • Parameter logging for troubleshooting errors.

  • Template code blocks for cleaner organisation.

By meeting the minimum Craft CMS version, you guarantee a stable base for the Vite plugin to build on. The integrated development experience will be smoother, frontend build performance will be optimised, and long-term maintenance will be easier.

So check your Craft CMS version prior to installing the plugin and upgrade if needed. The effort to update will pay dividends in the long run with a seamless Vite experience.

Node.js Version Required

To take full advantage of the speed and capabilities of Vite, your development environment will require Node.js version 14.18.0 or higher. This prerequisite is driven by the evolving nature of JavaScript tooling.

While earlier versions of Node may allow Vite to work initially, you'll miss out on performance improvements and encounter subtle bugs. Key advantages of Node 14.18.0+ include:

  • Support for logical assignment operators like ||= and ??= for less verbose code.

  • Promise-based fs/promises API for cleaner async filesystem access.

  • Full support for ESM modules without needing to enable flags.

Checking your Node.js version in advance avoids headaches when building and deploying. And upgrading enables your team to leverage the latest JavaScript syntax like optional chaining and nullish coalescing that Vite needs.

Satisfying the minimum Node.js requirement guarantees a robust development environment for the Vite plugin. Your team will benefit from faster builds, ES module support, and improved code quality when developing Craft sites.

So ensure your system meets the prerequisite Node.js 14.18.0+ version prior to installing the Vite plugin. While migrating Node versions may require some effort, it paves the way for an optimised frontend experience.

Installing the Vite Plugin

Using Composer to Install

The easiest way to install the Craft CMS Vite plugin is by using Composer, the PHP dependency manager. Composer allows you to quickly download and integrate the plugin into your Craft project.

Start by navigating to your project's root directory in the terminal. Then run the following command to tell Composer to fetch the latest version of the Vite plugin:

composer require craftcms/vite

Composer will take care of the rest. It will download the plugin files into the vendor folder and update composer.json and composer.lock.

Once finished, Composer will output confirmation that the Vite plugin was installed successfully. You should see something like:

./composer.json has been updated

./composer.lock has been updated

Downloading craftcms/vite (1.0.0)

Vite plugin installed successfully

Using Composer is the recommended way to install the plugin because it handles the file system changes and dependency management automatically. It also makes it easy to update the plugin later on.

After Composer finishes, don't forget to commit the modified composer.json, composer.lock and new vendor folder contents to version control. This ensures the plugin files are tracked and teammates can sync the dependencies.

Verifying Plugin Installation

Once Composer has run, verify that the Craft CMS Vite plugin installed correctly before proceeding further.

The quickest way to validate is by logging into the Craft control panel and checking the Plugins page. You should see "Vite" listed, ready to be enabled.

You can also scan the Requirements checker for any environment issues. If all system requirements are met, including minimum PHP version and Craft CMS version, the checker will display a "Ready to go" message.

Finally, check that the plugin files now exist within vendor/craftcms/vite folder. Opening composer.json should also reveal vite listed under "require".

Spot checking these areas takes little time but provides confidence that Composer grabbed the plugin properly. Don't skip this validation step or else cryptic errors could appear later on.

Troubleshooting Installation Issues

If the Vite plugin fails to install correctly, don't panic. A few common issues typically crop up but can be quickly resolved.

For example, if Composer displays dependency errors, run composer update to sync any version conflicts. Outdated packages in composer.lock likely need alignment.

Or you may see environment errors in Requirements checker or composer about minimum PHP or Craft CMS version not met. Double check your prerequisites and upgrade if needed.

Invalid composer.json or composer.lock files can also prevent proper plugin installation. Delete composer.lock, re-install dependencies and commit changes to fix.

Permissions issues may arise too if Composer can't write plugin files to the vendor folder. Adjust folder permissions to allow Composer to add the Vite plugin cleanly.

With a little trial and error, you'll get the Craft CMS Vite plugin properly installed via Composer. Just take note of any warning messages during the process to narrow down potential culprits.

Configuring the Vite Plugin

Environment and Build Paths

A key aspect of configuring the Craft Vite plugin involves setting up environment variables and configuring build output paths. This allows you to optimize builds for development vs production environments.

For example, you'll want to set NODE_ENV to "development" when coding locally. This disables minification and outputs readable code with hot module replacement.

For production, use NODE_ENV "production" instead. This minifies code for smaller file sizes and disables HMR for performance.

You can also configure the build.base public path where assets get emitted. For development, set to "/" for easy local URLs.

For production, consider a CDN path like "/cdn/assets/" to leverage caching and geo-distributed assets.

The Vite config file also allows defining separate outDirs for development and production builds.

For example:

outDir: NODE_ENV === "development" ? "web/assets" : "dist/assets"

This ensures builds target proper local vs. production destinations.

Taking time to configure environments and paths upfront saves headaches later. Your team can build using settings tailored for each use case.

Optimizing Build Settings

To get the fastest build speeds, leverage Vite's built-in caching and optimization capabilities.

Enable Vite's cache by setting cacheDir to a writable folder. This skips expensive re-builds of unchanged modules.

For assets, set build.rollupOptions.output.assetFileNames to include hashes or chunks in filenames. This enables long-term caching.

Also configure build.minify to "terser" to minify and compress final bundles for production.

Smaller settings like build.sourcemap and build.target also impact build performance and bundle size.

Beyond base Vite settings, the Craft plugin offers additional asset generation and optimization features.

For example, set generateSprite to auto-generate image sprite sheets. And enable compressedJs to gzip compress JavaScript.

With smart config, your Vite builds will maximize caching, compression and optimizations for the best end user experience.

Plugin-Specific Settings

The Craft Vite plugin offers some additional settings beyond base Vite to customize and extend functionality.

For example, set rootPath to indicate the web root path if Vite can't detect it automatically.

Use addCssToEntry to inject global CSS files into each page's entry point, avoiding extra network requests.

To have more control over entry generation, define entryPattern and entryTemplatePath values.

If using a CDN, set basePublicPath to add the CDN URL to asset references in templates.

There are also settings around webpack configuration, custom aliases, and HMR behavior - check the docs for specifics.
While Vite itself requires minimal config, judiciously using the plugin settings takes the developer experience to the next level for Craft projects.

Key Features of Vite

Faster Hot Module Replacement

One major benefit Vite provides is significantly faster hot module replacement (HMR). Instead of full page refreshes, Vite patches only the updated modules in-place.

This near instantaneous feedback loop accelerates development. No more losing component state or scrolling back to the right spot upon save. Changes are injected on-the-fly while you work.

Under the hood, Vite leverages native ES Modules and close coupling with your dev server. Updated modules fire events, triggering hot updates without refreshing.

For larger projects, optimized HMR manifest caching avoids re-calculating file dependencies on every change. Only needed imports re-render.

The end result is lightning fast real-time editing experiences. Changes appear instantly as you code. Vite's HMR speed crushes traditional bundlers, improving developer productivity.

Optimized On-Demand Importing

Another feature that makes Vite blazing fast is its optimized on-demand importing. Code splitting is built-in, so only necessary modules load.

For example, a Button component import won't bundle its dependencies like ripple effects or async loading logic. Those chunks split out and load only when needed.

Vite analyzes the import graph and splits your code into optimal chunks. Shared dependencies de-dupe into common bundles. Less code ships to the client by default.

This granular fragmentation also enables prefetching. Low priority chunks preload in idle time after initial render. No more waterfall loading effects.

The end result is lean, optimally timed module delivery for 60%+ faster load times. On-demand importing in Vite keeps apps fast.

Instant Server Start

Finally, Vite massively improves developer experience by providing nearly instant server starts.

Whereas traditional bundlers must index entire dependency graphs before serving, Vite servers only need access to index.html.

This lazy-loading of pages combined with native ES module imports allows spinning up dev environments in under 50ms.

Changes instantly appear when you save and refresh. No more grabbing coffee between restarts.

Vite's Esbuild plugin takes things even further, pre-bundling dependencies during install. Server can simply fetch from disk, skipping bundling completely.

The end result is an unmatched edit-refresh loop. Tweak code and see changes in real-time with reliable instant reloads. Vite's speed unleashes creativity.

Working with Assets in Vite

Importing Asset Files

One advantage of Vite is handling static assets like images and fonts is a breeze. Simply import asset files directly into your components.

For example:

import logo from './logo.png'

Vite automatically optimizes assets on-the-fly. Image files import as strings pointing to optimized URLs.

Reference assets directly in templates:

<img src={logo} />

For CSS, import the asset then reference via the url() function:

@import './logo.png'

.logo {

background: url('./logo.png')

}

Vite handles minification, caching, and serving. No need for copy plugins or asset loaders.

Assets also receive version hashes for cache busting. Just import and reference normally and Vite handles the heavy lifting!

Asset Processing and Optimization

For asset optimization beyond Vite's built-in capabilities, leverage plugins.

For example, vite-imagetools pre-processes images like optimizing SVG and stripping metadata. This improves load speed and optimizes images using Craft CMS. 

Or use vite-plugin-spritesmith to generate sprite sheets from folders of images, reducing requests.

The excellent @vitejs/plugin-vue offers image compression, webp support, and progressive image loading.

For icons, vite-plugin-react-svg imports SVGs as React components with tree shaking benefits.

And vite-imagetools has resize, scale, and compress capabilities perfect for responsively delivering pictures.

With its flexible plugin system, Vite can handle all asset processing and optimizations needs right from your project.

Working with Fonts and Other Assets

The beauty of Vite is it works seamlessly with fonts, videos, and other media just like JavaScript and images.

For fonts, simply import the files in CSS:

@import './fonts/OpenSans.woff2'

Then specify in properties like font-family. Vite handles minification and optimization.

For videos, import the files then set the video source:

import intro from './intro.mp4'

//...

<video src={intro} />

Audio, PDFs, sprites, animations also effortlessly import. Vite recursively optimize any assets referenced.

This unified asset handling avoids needing other tools. With Vite, fonts, videos and more enhance sites without complexity.

Deploying a Vite Site

Production Build Process

To deploy a Vite site live, first generate an optimized production build. This bundles and minifies code for peak performance.

Run vite build to kick off production bundling. Vite will crawl your entry points, analyze imports, and output optimized chunks.

CSS and JavaScript minify via Terser. Hashes append to asset filenames for caching. Bundles tree shake to exclude unused code.

Sourcemaps, development hints, and debugging helpers strip out. Only minimal production-ready code ships.

Under the hood, features like HTTP/2 server push, dynamic import hoisting, and preload directives optimize delivery.

The process completes quickly thanks to Esbuild pre-bundling dependencies on install. Vite re-bundles only your source code.

When finished, you'll find an optimized dist folder containing index.html and minified assets ready for deployment.

Deployment Workflow

With optimized Vite output generated, deploy the dist folder to your production server or hosting provider.

On Vercel or Netlify, linking to your Git repo automatically builds and deploys changes. Connect to the dist folder as the deploy root.

For AWS, copy files to an S3 bucket serving assets through CloudFront. Automatic invalidations refresh the CDN.

DigitalOcean App Platform offers one-click deploys from GitHub. Automatically build and deploy upon push.

Most shared hosts support FTP/SFTP file transfers. Upload the dist contents to the public html folder.

However deployed, Vite assets require no special handling. It's static HTML, JS, and CSS ready for production.

Optimizing for Production

A few key tips will optimize your Vite site for the fastest production performance

Leverage long-term caching by enabling asset hash names. CDNs and browsers can heavily cache unchanged files.

Shrink JS/CSS footprints by enabling build.minify in vite.config.js. Use Brotli/gzip compression where possible.

Split larger bundles into smaller chunks using dynamic import() to parallelize. Prefetch low priority routes.

Lazy load below-the-fold components to minimize initial JavaScript. Defer non-critical CSS and JavaScript.

Set up error monitoring like Sentry to catch errors. And enable standalone mode for self-contained builds.

With smart performance best practices, Vite sites easily achieve the fastest perceived load times. Your users will love the experience!

Migrating from Webpack

Comparing Vite and Webpack

Before migrating a Webpack project to Vite, it helps to contrast their architectures and capabilities.

Webpack is a traditional bundler that builds a dependency graph on startup. It requires extensive configuration as all assets pass through its pipeline.

Vite leverages native ES modules and pre-bundles dependencies. Its dev server starts instantly without bundling. Configuration is minimal.

Webpack bundles all code into a single bundle without code splitting. Vite code splits automatically via dynamic import().

Webpack handles HTML, CSS and assets via loaders. Vite directly imports files and handles asset optimization.

For HMR, Webpack fully refreshes changed modules. Vite surgically hot updates only affected components.

In summary, Vite provides a faster, leaner development experience. So migrating from Webpack unlocks huge productivity wins.

Step-by-Step Migration Process

When migrating from Webpack to Vite, follow these steps:

  1. Install Vite and external dependencies from package.json.

  2. Copy over key Webpack configuration like aliases, resolve paths, and globals.

  3. Migrate loaders that have Vite equivalents like file-loader to file assets.

  4. Split single bundle entry chunk into multiple dynamic entries via import().

  5. Move Webpack plugins with Vite equivalents like html-webpack-plugin.

  6. Update module imports from CommonJS to ESM syntax.

  7. Refactor async module loading from custom Webpack logic to native dynamic import().

  8. Test rigorously and optimize imports and server configurations for production.

  9. Deploy a preview build and iterate until feature parity with Webpack.

With focus and iteration, the migration process smooths out the core differences between the bundlers.

Handling Migration Issues

During migration, a few issues may arise:

Legacy, unmaintained plugins may lack Vite equivalents. Evaluate if still needed, or find alternatives that provide similar capabilities.

Complex Webpack logic like multi-compiler configs may be challenging to port over. Carefully analyze and aim for simplification where possible.

Custom client-side runtime requirements like accessing the Webpack bundle object will need refactors. Think of native JavaScript alternatives.

Code relying heavily on CommonJS patterns like runtime requires() for async loading needs updates to leverage ESM dynamic imports.

Migration takes time and patience. But by tackling issues diligently, your new Vite setup will soon outpace the original Webpack project. The benefits are worth the temporary hassle.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat