Vite / Rollup Static Asset Copy Hook

25 Views Asked by At

Is there a hook in Vite or Rollup to provide access to any or all static assets that get copied automatically?

I am writing a Vue 3 app. Vue automatically copies all static asset files under the "~/public" folder (at the root) of any Vue project. I would like to know when/which entries are being copied at build time (vite build). I just need a rather simple hook to run a very simple function. Ideally, something like this...

Example/Pseudocode

**/some/hook/or/plugin.js

export function observe(pathname, source) {  // intercepts on file "~/public/assets/listings.js"
    if (pathname !== 'assets/listings.js') return source;
    return utilities.interpolate(source)({ tokenX: 'value to supplant in file' });
};

~/vite.config.js

export default defineConfig({
    plugins: [
        vue()
    ],
    resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    staticAssetStuff: {
        hooks: [
            observe,
        ]
    }
});

Example ~/public/assets/listings.js

export default [
  'This is a listing where {tokenX} needs to get interpolated',
  ...more
];

Context

This is because I need to interpolate certain values into placeholders that exist in a "~/public/assets/listings.js" file. In short, it is because a script, which must remain as a static asset in the public directory, needs to import the "listings.js" file. The challange is that this needs to happen after the bundling process takes place. I have searched high & low across the masses of documentation for both Vite and Rollup and have not seen anything to hook into the asset-copy phase in Vue/Vite; but then, again, your brain gets numb after looking through that much documentation :-P The only other thing I can think of is to create a package.json postbuild script that just crawls the ~/dist directory, finds assets, and then operates on them. I just thought, since Vite / Rollup have EVERY hook under the sun, that this too would be a hook. It seems like, if you were to have only one hook in Vite / Rollup, this would be the one!

Is something like this possible?

Please help!

0

There are 0 best solutions below