Vite: Set `assetFileName` based upon directory name

Given the project structure below, Vite will output both CSS files as index.<hash>.css which makes them difficult to debug. I’d like to alter the config to use the directory name if the file name is index:

src/
--pages/
----Home/
------index.jsx
------style.css
----NotFound/
------index.jsx
------style.css

Unfortunately, the param of assetFileNames seems to be quite barren of usable information about the source location.

// vite.config.js
import preact from '@preact/preset-vite';

export default defineConfig({
    build: {
        rollupOptions: {
            output: {
                assetFileNames: (assetInfo) => {
                    console.log(assetInfo);
                    return 'assets/[name]-[hash][extname]';
                },
            }
        }
    }
});
{
  name: 'index.css',
  source: '<My CSS content>',
  type: 'asset'
}

Is there any way to get further context from assetInfo, such as the original file path?

chunkFileNames, for instance, gets the facadeModuleId property which contains the original file path which is incredibly useful here; it ensures NotFound/index.jsx is output as NotFound-<hash>.js, rather than index-<hash>.js:

chunkFileNames: (assetInfo) => {
    const name = assetInfo.name == 'index'
        ? path.basename(path.dirname(assetInfo.facadeModuleId))
        : assetInfo.name;
    return `${name}-[hash].js`;
}

Leave a Comment