Sub topic 14
Module Metadata with import.meta
Every ES module can find out where it lives. A classic script has no reliable way to do this, and CommonJS used the injected variables __dirname and __filename. ES modules get a special object called import.meta, which the host environment (the browser, Node.js, Deno, or a bundler) fills with information about the current module.
This chapter assumes you know the import and export syntax, that you have run modules in both the browser and Node.js, and that you are comfortable with async/await and the URL class.
What import.meta Is
import.meta is a meta-property: a piece of syntax that looks like property access on import but is not. import is a keyword, not a variable, so you cannot write const x = import;. The expression import.meta as a whole evaluates to an ordinary object.
The language specification makes three guarantees about that object:
- Each module instance gets its own
import.metaobject. Two modules never share one. - The object is created lazily, the first time a module reads
import.meta, and the same object comes back every time after that. - Its prototype is
null, and the host decides which properties it holds. The language itself defines no properties.
The third point matters most. Everything you read from import.meta comes from the environment, so support depends on which runtime or tool runs your code.
// inspect.js (run as an ES module)
console.log(Object.getPrototypeOf(import.meta)); // null
console.log(import.meta === import.meta); // true
console.log(Object.keys(import.meta)); // host-defined, e.g. [ 'dirname', 'filename', 'resolve', 'url' ] in recent Node.jsOnly Modules Can Use It
import.meta is only valid in module code. In a classic <script> or a CommonJS file it is a SyntaxError, raised when the file is parsed, before any line runs. A try/catch cannot guard against it.
// legacy.cjs
console.log(import.meta.url);
// SyntaxError: Cannot use 'import.meta' outside a moduleIf you see this error, the file is being loaded as a script or as CommonJS. Check the type="module" attribute in the browser, or the file extension and the "type" field in package.json in Node.js.
import.meta.url
import.meta.url is the one property every major host provides. It holds the module's full URL as a string, not a file path.
| Environment | Example value of `import.meta.url` |
|---|---|
| Browser, external module | `https://example.com/js/widgets/chart.js` |
| Browser, inline `<script type="module">` | The URL of the HTML document |
| Node.js | `file:///home/ana/app/src/config.js` |
| Deno | `file:///home/ana/app/mod.ts` or an `https:` URL |
Because it is a URL, the main way to use it is as the base argument to new URL(). That resolves a relative path against the module's own location instead of against the page or the current working directory.
In the browser
Relative URLs passed to fetch() resolve against the document, not the script. Suppose a module in /js/widgets/ fetches './template.html'. If the page is /index.html, the request goes to /template.html and returns a 404. Anchoring the path to import.meta.url fixes this:
// /js/widgets/card.js
const templateUrl = new URL('./template.html', import.meta.url);
const response = await fetch(templateUrl);
export const template = await response.text();The module now works on any page that imports it, at any depth of the site.
In Node.js
Relative paths passed to fs functions resolve against process.cwd(), the directory the user launched Node.js from. That is a common source of bugs that only appear when someone runs the script from another folder. Node's fs functions accept URL objects directly, so the same pattern works:
// src/config.js
import { readFile } from 'node:fs/promises';
const url = new URL('./settings.json', import.meta.url);
const text = await readFile(url, 'utf8');
export const settings = JSON.parse(text);Replacing __dirname and __filename
ES modules in Node.js do not have __dirname or __filename. When an API needs a path string instead of a URL, convert with fileURLToPath() from node:url:
// src/paths.js
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
console.log(filename); // /home/ana/app/src/paths.js
console.log(dirname); // /home/ana/app/src
console.log(path.join(dirname, 'templates', 'email.html'));Node.js 20.11 and later also provide import.meta.filename and import.meta.dirname, which hold these values directly. They exist only for file: modules, so they are undefined for modules loaded from other URL schemes.
import.meta.resolve()
import.meta.resolve(specifier) returns the absolute URL string that a specifier would resolve to if this module imported it. It runs synchronously and loads nothing. Browsers support it, and so does Node.js from version 20.6.
// src/main.js
console.log(import.meta.resolve('./utils.js'));
// file:///home/ana/app/src/utils.js
console.log(import.meta.resolve('lodash-es'));
// file:///home/ana/app/node_modules/lodash-es/lodash.jsIt applies the same rules as import: import maps in the browser, and node_modules lookup plus the package exports field in Node.js. That makes it useful when you need a dependency's location, for example to hand a URL to a Worker or to find a package's bundled asset. A relative specifier always produces a URL, even if no file exists there. A bare specifier that cannot be resolved throws.
Detecting the Entry Module
Python has if __name__ == '__main__', and CommonJS has require.main === module. ES modules have no standard equivalent. Deno and Bun provide import.meta.main, and recent Node.js releases have added it too. The portable approach in Node.js compares the module's path with the script Node.js was started with:
// src/cli.js
import { fileURLToPath } from 'node:url';
import { realpathSync } from 'node:fs';
export function greet(name) {
return `Hello, ${name}`;
}
const isEntry =
process.argv[1] !== undefined &&
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
if (isEntry) {
console.log(greet(process.argv[2] ?? 'world'));
}Running node src/cli.js Ana prints a greeting. Importing greet from another module prints nothing. realpathSync resolves symlinks, which globally installed CLI tools often go through.
Tool-Defined Properties
Bundlers and dev servers add their own properties because the object is host-defined. Vite provides import.meta.env for environment variables and import.meta.hot for hot module replacement. webpack provides import.meta.webpackHot. These properties are replaced at build time and do not exist when the same file runs directly in Node.js or a browser.
// Works under Vite; undefined in plain Node.js or the browser
const apiBase = import.meta.env?.VITE_API_BASE ?? 'http://localhost:3000';Bundlers also recognize the pattern new URL('./logo.png', import.meta.url). They copy the asset into the build output and rewrite the URL so it points at the copy. The rewrite only works when the path is a string literal. If you build the path at runtime, the bundler cannot see the file.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: Cannot use 'import.meta' outside a module` | File loaded as a classic script or CommonJS | Use `type="module"`, `.mjs`, or `"type": "module"` |
| `ReferenceError: __dirname is not defined` | CommonJS habit carried into an ES module | Use `import.meta.dirname` or `fileURLToPath` |
| File found only when run from one folder | Relative `fs` path resolved against `process.cwd()` | Use `new URL(path, import.meta.url)` |
| Asset 404 in the browser | `fetch` path resolved against the document | Anchor the path to `import.meta.url` |
| `import.meta.env` is `undefined` | Code ran outside the bundler that defines it | Provide a fallback or inject config another way |
Exercise
A module at /js/lib/i18n.js runs fetch('./strings.json') and gets a 404 when used from https://example.com/app/page.html. Which URL was requested, and how do you change the code so it loads /js/lib/strings.json?
Show answer
The relative path resolves against the document, so the browser requested https://example.com/app/strings.json. Change the call to fetch(new URL('./strings.json', import.meta.url)). The path then resolves against https://example.com/js/lib/i18n.js and becomes https://example.com/js/lib/strings.json.
Exercise
Why does wrapping console.log(import.meta.url) in try/catch not stop the error in a CommonJS file, and what does this tell you about where the error comes from?
Show answer
In non-module code, import.meta is invalid syntax. The error is a SyntaxError thrown while the file is parsed, before any code runs, including the try statement. It shows that module-only syntax is checked when the source is compiled, not when it executes.
Exercise
Write a Node.js ES module that logs the absolute path of a file named data.csv stored next to the module, and works on Node.js versions older than 20.11.
Show answer
import { fileURLToPath } from 'node:url'; console.log(fileURLToPath(new URL('./data.csv', import.meta.url))); This avoids import.meta.dirname, which older versions lack, and fileURLToPath produces a correct path on every platform.