âšī¸ Know Your Module’s URL, Resolve Paths
Need to load assets relative to current file? import.meta gives you module URL, hot reload status, and more.
đ import.meta.url
// main.js
console.log(import.meta.url);
// "file:///C:/project/src/main.js" (Node.js)
// "https://example.com/js/main.js" (browser)
// Get directory of current module
const modulePath = new URL('.', import.meta.url).pathname;
// Load sibling file dynamically
const data = await fetch(new URL('./data.json', import.meta.url));
// Construct asset path
const imgUrl = new URL('./images/logo.png', import.meta.url).href;
đ¯ Vite/import.meta.env
// Vite exposes environment variables
if (import.meta.env.DEV) {
console.log('Development mode');
}
if (import.meta.env.PROD) {
console.log('Production mode');
}
const apiUrl = import.meta.env.VITE_API_URL;
// Base URL
const baseUrl = import.meta.env.BASE_URL;
// Check hot module replacement
if (import.meta.hot) {
import.meta.hot.accept(() => {
console.log('Module updated');
});
}
đĄ Use Cases
- Load assets relative to current module (no relative path guesswork)
- Environment detection (dev/prod/test)
- Hot Module Replacement (HMR) handlers
- Dynamic import with resolved paths
“Moved components to subfolder. All relative imports broke. import.meta.url fixed it â always loads from correct location. No more ../../../ path hell.”
