How to enable brotli compression for static resources in Vaadin?

97 views Asked by At

I like to put some of the CSS file under the static java resources folder ${project}/src/main/resources/META-INF/resources in Vaadin so I can share it across the different themes and can be loaded and exchanged dynamically at runtime when needed. See also https://vaadin.com/docs/latest/styling/advanced/loading-styles-dynamically

My Problem: When I do now a production build I noticed that these css files in the resource folder get not compressed for brotli.Only those which are in the ${project}/frontend/themes folder seems to be picked up. Any idea what can be done so these css files will also be prepared?

1

There are 1 answers

0
megloff On

Vaadin offers to overwrite the vite config in vite.config.ts. There I could add a plugin to compress the additional files.

e.g. vite.config.ts :

import brotli from "rollup-plugin-brotli";
import {readdir, readFile} from 'node:fs/promises';
import {resolve} from 'node:path';

// helper function to read files recursively
async function * getFiles(dir) {
    for (const dirent of await readdir(dir, {withFileTypes: true})) {
        const res = resolve(dir, dirent.name);
        if (dirent.isDirectory()) {
            yield * getFiles(res);
        } else {
            yield res;
        }
    }
}

let targetfiles : string[] = []; 
// read the additional css file directory recursively 
// and add it as absolute file paths to the target files list.
for await (const file of getFiles(myAdditionalCSSFilesPath)) {
    if (file.endsWith(".css")) {
       targetfiles.push(file);
    }
}

const customConfig: UserConfigFn = (env) => ({
  // Here you can add custom Vite parameters
  // https://vitejs.dev/config/
    plugins: [
      brotli({
        additional : targetfiles,
      }),
    ]
});