Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Assets and CSS

Asset URLs and Glob Imports

Use import.meta.glob to import many files at once, choose eager or lazy loading, pull query and import options, build asset lists with new URL, and understand base and static analysis rules.

Sometimes you do not know the exact file at the time you write the code: a gallery that shows every image in a folder, a blog that loads every Markdown file, a router that turns files into pages. Vite is a static tool, so it cannot follow import('./pages/' + name) safely. It offers two answers: the new URL(..., import.meta.url) pattern for single assets, and import.meta.glob for sets of files. This lesson covers both, and the static analysis rules that go with them.

Vite is not installed on this site, so the Vite calls are read-only. The runnable examples model glob matching and the generated code so you can see what Vite produces.

import.meta.glob

JavaScript
const modules = import.meta.glob('./pages/*.js');

At build time Vite replaces that call with an object whose keys are the matched file paths and whose values are functions that import each file:

JavaScript
// What Vite generates (simplified)
const modules = {
  './pages/about.js': () => import('./pages/about.js'),
  './pages/home.js': () => import('./pages/home.js'),
};

You then call the functions you need, so each file becomes its own lazy chunk and loads only on demand:

JavaScript
const loadAbout = modules['./pages/about.js'];
const mod = await loadAbout();
console.log(mod.default);

This is also how file-based routing works in many meta-frameworks: every file in pages/ becomes a route and a lazy chunk.

Eager loading

If you want all modules loaded up front, pass eager: true. The values are then the modules themselves, not functions:

JavaScript
const modules = import.meta.glob('./icons/*.js', { eager: true });
// { './icons/a.js': { default: ..., name: ... }, ... }

Eager imports are bundled into the importer, which is fine for small sets and bad for large ones.

Named imports and import option

Pick one export instead of the whole module:

JavaScript
const titles = import.meta.glob('./posts/*.js', { import: 'title', eager: true });
const defaults = import.meta.glob('./posts/*.js', { import: 'default' });

Query: raw text and asset URLs

The query option adds a suffix to each import, which combines glob with the import suffixes from Static Assets and the public Directory:

JavaScript
// Read every Markdown file as a string
const posts = import.meta.glob('./posts/*.md', { query: '?raw', import: 'default', eager: true });

// Get the URL of every image
const images = import.meta.glob('./gallery/*.{jpg,png,webp}', {
  query: '?url',
  import: 'default',
  eager: true,
});

The result for images is { './gallery/a.jpg': '/assets/a-3f9a2c1b.jpg', ... }, ready to put into <img src>.

Patterns

import.meta.glob uses fast-glob syntax (picomatch):

Pattern Matches
./dir/*.js JS files directly in dir
./dir/**/*.js JS files at any depth
./dir/*.{png,jpg} Either extension
!./dir/*.test.js Exclude (negative pattern)
['./a/*.js', '!./a/_*.js'] Array: include and exclude
/src/pages/*.js Root-absolute path
@/pages/*.js Alias paths work

Paths are resolved relative to the file with the call, and keys in the result keep the same style as your pattern (relative stays relative, absolute stays absolute).

A glob matcher as a model

This stand-in implements a minimal matcher (single *, ** and {a,b}) and the key-to-function mapping. It teaches the shape of the result; Vite's matcher handles far more syntax.

Node.js Stand-in: what a glob call produces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Static analysis rules

import.meta.glob is processed at compile time, so its arguments must be literals. Vite cannot read variables:

JavaScript
const dir = './pages';
import.meta.glob(dir + '/*.js');      // Error: arguments must be string literals
import.meta.glob(`${dir}/*.js`);      // Error too
import.meta.glob('./pages/*.js');     // OK

Other rules:

  • All patterns must start with ./, ../, / or an alias.
  • The options object must be a literal, too.
  • Matching happens when Vite starts or builds; new files appear after the file watcher notices them (HMR updates the module).

Dynamic imports with variables

A plain dynamic import with a variable is allowed only in a restricted form:

JavaScript
const mod = await import(`./locales/${lang}.js`);

Vite turns this into a glob-like import behind the scenes. It requires a relative or alias path starting with ./ or ../, a file extension, and it cannot cross into a different folder with a variable part like ../${name}. Importing every file this way creates a chunk per file in the matched folder. For clarity and control, prefer an explicit import.meta.glob.

new URL for a single asset

For one known asset, no glob is needed:

JavaScript
const logoUrl = new URL('./assets/logo.svg', import.meta.url).href;

Vite recognizes this exact pattern: a string literal relative path and import.meta.url. In a build the file is hashed and the string is replaced with its final URL. It also works for workers: new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }).

Template strings with a variable part are supported for the same reason as dynamic imports (a simple folder and extension), but a plain variable is not:

JavaScript
new URL(`./assets/${name}.png`, import.meta.url).href;   // OK: a glob is generated
new URL(path, import.meta.url);                          // Not analyzed, left as is

Keep in mind that new URL(..., import.meta.url) does not work during server-side rendering the same way; for SSR use imports.

base and public paths

All of these URLs are prefixed with base in production. For a site at https://example.com/app/, set base: '/app/' and an asset becomes /app/assets/logo-3f9a2c1b.svg. With base: './' URLs are relative to the file that uses them, so the build can be placed anywhere. For runtime-computed public URLs, use import.meta.env.BASE_URL:

JavaScript
const url = import.meta.env.BASE_URL + 'data/cities.json';

experimental.renderBuiltUrl lets you rewrite asset URLs completely (CDN hosts, runtime base).

Here is a small realistic use. It builds a gallery from every image in a folder.

JavaScript
const images = import.meta.glob('/src/gallery/*.{jpg,png,webp}', {
  query: '?url',
  import: 'default',
  eager: true,
});

const gallery = document.querySelector('#gallery');
for (const [path, url] of Object.entries(images)) {
  const name = path.split('/').pop();
  gallery.insertAdjacentHTML('beforeend', `<img src="${url}" alt="${name}" loading="lazy">`);
}

Adding a picture to src/gallery/ shows it on the page with no code change, and in a build each image receives a hashed name.

This runnable page models that loop with data in place of imported URLs:

Gallery from a glob result (model)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the values of an object returned by import.meta.glob('./pages/*.js') without options?

    By default each value is a function that imports the file lazily, so each file becomes its own chunk.
  2. 2. How do you get the URL of every image in a folder at build time?

    Combine the ?url query with import: 'default' and eager: true to get a map of path to URL.
  3. 3. Why does import.meta.glob(dir + '/*.js') fail?

    Vite expands glob calls at build time, so patterns must be string literals.
  4. 4. Which pattern correctly excludes files starting with an underscore?

    An array of patterns with a leading ! excludes matches.

Summary

  • import.meta.glob turns a literal pattern into an object of lazy imports; eager: true loads them up front.
  • Use import to pick one export and query (?raw, ?url) to change how each file loads.
  • Patterns and options must be literal strings; negative patterns exclude files.
  • new URL('./file', import.meta.url) handles single assets, and base prefixes all asset URLs in production.
  • Dynamic imports with variables are limited to a relative folder with a file extension.

Next: Anatomy of a Vite Plugin