Vite JSON & import.meta.glob
Two handy Vite features for working with data and many files at once: importing JSON directly, and importing whole groups of modules with import.meta.glob.
Importing JSON
{
"name": "ExcelTAD",
"version": "1.4.0",
"features": ["courses", "quizzes", "playgrounds"]
}// src/main.js
import config from './config.json'; // whole object
import { version } from './config.json'; // named import of a top-level key
console.log(config.name, version);Named imports from JSON are a Vite convenience: every top-level key becomes a named export. That helps tree-shaking — if you only import version, the bundler can drop the rest.
What Vite does under the hood is simply turn the JSON into an ES module. You can do the same by hand:
const json = '{"name":"ExcelTAD","version":"1.4.0","features":["courses","quizzes"]}';
function jsonToModule(text) {
const data = JSON.parse(text);
const named = Object.keys(data)
.map((k) => `export const ${k} = ${JSON.stringify(data[k])};`)
.join('\n');
return `${named}\nexport default { ${Object.keys(data).join(', ')} };`;
}
const code = jsonToModule(json);
console.log(code);
(async () => {
const mod = await import('data:text/javascript,' + encodeURIComponent(code));
console.log('version =', mod.version, '| features =', mod.default.features.length);
})();export const name = "ExcelTAD";
export const version = "1.4.0";
export const features = ["courses","quizzes"];
export default { name, version, features };
version = 1.4.0 | features = 2
| Option | Effect |
|---|---|
json.namedExports (default true) |
Allow import { key } from './x.json' |
json.stringify (default 'auto') |
Large JSON is emitted as JSON.parse("..."), which parses faster than a JS object literal |
Note: Only top-level keys that are valid identifiers become named exports. A key like
"my-key"is still reachable through the default export.
import.meta.glob
Suppose you have one markdown or module file per blog post, per locale, or per page, and you don't want to write fifty import lines. import.meta.glob matches files with a glob pattern at build time:
const modules = import.meta.glob('./pages/*.js');Vite turns that into code roughly like:
const modules = {
'./pages/about.js': () => import('./pages/about.js'),
'./pages/home.js': () => import('./pages/home.js'),
};By default each value is a lazy loader function — every file becomes its own chunk, loaded only when you call it. That's perfect for routing:
// What import.meta.glob('./pages/*.js') produces (simulated with data: URLs)
const mk = (src) => () => import('data:text/javascript,' + encodeURIComponent(src));
const pages = {
'./pages/about.js': mk("export default () => 'About us'"),
'./pages/home.js': mk("export default () => 'Welcome home'"),
};
async function render(path) {
const key = `./pages/${path}.js`;
const loader = pages[key];
if (!loader) return console.log(path, '-> 404');
const page = await loader();
console.log(path, '->', page.default());
}
(async () => {
console.log('available:', Object.keys(pages).join(', '));
await render('home');
await render('about');
await render('blog');
})();available: ./pages/about.js, ./pages/home.js
home -> Welcome home
about -> About us
blog -> 404
Options
// Eager: import everything up front (no lazy chunks)
const all = import.meta.glob('./locales/*.json', { eager: true });
// Only one named export
const titles = import.meta.glob('./posts/*.js', { import: 'title', eager: true });
// Raw strings (e.g. markdown files)
const docs = import.meta.glob('./docs/*.md', { query: '?raw', import: 'default' });
// URLs to assets
const icons = import.meta.glob('./icons/*.svg', { query: '?url', import: 'default', eager: true });
// Multiple patterns and negation
const mods = import.meta.glob(['./widgets/*.js', '!**/*.test.js']);| Option | Values | Effect |
|---|---|---|
eager |
false (default) / true |
Lazy loader functions vs. already-imported modules |
import |
'default', 'title', … |
Pick one export instead of the namespace |
query |
'?raw', '?url', { foo: 'bar' } |
Append a query to every import |
base |
'./src' |
Base path used for the returned keys |
Warning: Arguments must be literal strings —
import.meta.glob(myVar)does not work, because Vite expands the pattern at build time, not at runtime.
Eager mode in practice
With eager: true the result is a plain object of modules. A common use is loading translation files:
// Simulated result of import.meta.glob('./locales/*.json', { eager: true, import: 'default' })
const locales = {
'./locales/en.json': { hello: 'Hello', bye: 'Goodbye' },
'./locales/vi.json': { hello: 'Xin chào', bye: 'Tạm biệt' },
};
const messages = Object.fromEntries(
Object.entries(locales).map(([path, data]) => [path.match(/(\w+)\.json$/)[1], data])
);
const t = (lang, key) => messages[lang]?.[key] ?? key;
console.log(Object.keys(messages));
console.log(t('vi', 'hello'), '/', t('en', 'bye'), '/', t('en', 'missing'));["en","vi"]
Xin chào / Goodbye / missing
Glob vs. dynamic import with variables
You can also write import(\./locales/${lang}.js`)— Vite supports variables in dynamic imports when the pattern is relative and has a file extension.import.meta.globis the more explicit, more flexible choice (eager mode,?raw`, choosing exports, listing keys).
Tip: Keys are file paths, so you can list available pages, posts or icons without hard-coding them — ideal for generating a menu.
Test yourself
What does import.meta.glob('./pages/*.js') return by default?
- An array of file names
- An object of path → lazy loader functions
- An object of path → module namespaces
- A single merged module
Why can't you call import.meta.glob(patternVariable)?
- Variables are slow
- The pattern is expanded at build time, so it must be a literal
- Globs only work in tests
- Only JSON files are allowed
With Vite, import { version } from './package.json'…
- Fails; JSON has no named exports
- Works; top-level keys become named exports
- Imports the file URL
- Requires a plugin