Access vite import.meta.glob image URL in JS

This might be more of a Vite question, but I can’t seem to find anything online. At the top of the default app.js file we have

import.meta.glob([
  '../images/**',
  '../fonts/**',
]);

If I want to get an image URL in javascript I have been using import audio_3 from '../audio/3.mp3'; but this throws the warning (!) /app/public/wp-content/themes/skillcheck/resources/audio/3.mp3 is dynamically imported by /app/public/wp-content/themes/skillcheck/resources/js/app.js but also statically imported by /app/public/wp-content/themes/skillcheck/resources/js/app.js, dynamic import will not move module into another chunk.

Is there a better way to get the image URLs from the /build/assets folder?

Did a little more digging and it seems like I might have found my own solution. Just add { eager: true } to the import.meta.glob call. Then you can access the assets by path as seen below. Please let me know if there is a better way.

const assets = import.meta.glob([
  '../audio/**',
  '../videos/**',
  '../images/**',
  '../fonts/**',
], { eager: true });

console.log(assets['../audio/3.mp3'].default);

Looks like eager is the way to go :+1:

I’m thinking we’ll probably want to get Sage updated to use that — at least for images. I’ll also get the docs updated with an example.

Thanks for the follow up :pray:

1 Like

PR: 🩹 Enable eager loading for images and fonts by retlehs · Pull Request #3245 · roots/sage · GitHub

1 Like