Vite - Local Plugin

06/27/2021, Sun
Categories: #Tooling #javascript
Tags: #frontend

Custom File Type Change Detection

Vite has a plugin system where a transform may be performed on file type changes in the following:

https://vitejs.dev/guide/api-plugin.html#transforming-custom-file-types

Even though the documentation states that transforms might be performed on "custom file types", attempts to listen to changes for file types other than the common web assets type (.js, .ts, .html, .css) will not work.

One must use the handleHotUpdate method to listen to "custom file types". There will be two files which configuration will need to be applied: vite.config.js and a new plugin definition file for detecting changes.

For this example, in vite.config.js, a local plugin, 'custom-file-type.js, will be imported and inserted into an array and then called.

// vite.config.js
import { defineConfig } from "vite";

import myPlugin from "./custom-file-type";

export default defineConfig({
    plugins: [myPlugin()]
});

Now the plugin 'custom-file-type.js' has a key of 'handleHotUpdate' method defined to listen to custom file types. The 'File' is destructured in the method's argument, and this value yields the filename with extension which can be read to discern which file type changed.

// Plugin - custom-file-type.js - Listen to external file types
export default function myPlugin() {
    return {
        name: 'custom-file-type',
        handleHotUpdate({ file }) {
            if (file.endsWith(".someextension")) {
               console.log("Custom extension type change.")
            }
        }
    }
}