> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Module variables

This section covers all variables available in code compiled with Rspack. Modules will be able to access specific data from the compilation process through `module` and other variables.

## CommonJS

### module.loaded

`false` means that the module is being executed, `true` the synchronous execution has been completed.

### module.id

Current module ID.

```js title=src/main.js
module.id === require.resolve('./src/main.js'); // true
```

### module.hot

Indicates whether or not hot module replacement is enabled and provides an interface to the process. See the [HMR API page](/api/runtime-api/hmr.md) for details.

### global

See [node.js global](https://nodejs.org/api/globals.html#globals_global) for details.

Rspack will replace the global with a proxy object and handle compatibility issues in it.


```js title=Source
global['property']
```
```js title=Compiled
__webpack_require__.g['property'];

// webpack/runtime/global
__webpack_require__.g = (function () {
  // compatibility code
})();
```

### \_\_filename

Depends on the configuration [`node.__filename`](/config/node.md#node__filename).

- `false`: undefined
- `mock`: equal to `'/index.js'`
- `true`: [NodeJs \_\_filename](https://nodejs.org/api/modules.html#__filename)

If used inside an expression that is parsed by the Parser, the configuration option is treated as `true`.


```js title=Source
__filename
```
```js title=Compiled
'src/main.js';
```

### \_\_dirname

Depends on the configuration [`node.__dirname`](/config/node.md#node__dirname).

- `false`: undefined
- `mock`: equal to `'/'`
- `true`: [NodeJs \_\_dirname](https://nodejs.org/api/modules.html#__dirname)

If used inside an expression that is parsed by the Parser, the configuration option is treated as `true`.


```js title=Source
__dirname
```
```js title=Compiled
'src';
```

## import.meta (ESM) \{#import-meta}

The `import.meta` exposes context-specific metadata to a JavaScript module, such as the URL of the module. It is only available in modules that support ESM ([module type](/misc/glossary.md#module-type) is `javascript/auto` or `javascript/esm`).

Normally, unknown `import.meta` metadata is replaced with `undefined` by default. When using [ESM output](/guide/features/esm.md), [`module.parser.javascript.importMeta`](/config/module-parser.md#javascriptimportmeta) defaults to `'preserve-unknown'`, so unknown metadata is preserved for runtime evaluation. You can also use the object form of `module.parser.javascript.importMeta` to control known `import.meta` properties individually.

Rspack statically analyzes `import.meta` properties and replaces them with concrete values at compile time, so dynamic access to `import.meta` (e.g., `Object.keys(import.meta)`) is not supported and will emit a warning. You should access metadata on `import.meta` via property access or destructuring assignment.


```js title=Source
// Will emit a warning
Object.keys(import.meta);
// typeof access is allowed
typeof import.meta;
// Property access is allowed
import.meta.url;
// Destructuring assignment is allowed
let { url } = import.meta;
```
```js title=Compiled
// Warning
Object.keys({});

('object');

('file:///project/index.js');

let { url } = { url: 'file:///project/index.js' };
```

### import.meta.url

Returns the absolute `file:` URL string of the current module.


```js title=Source
import.meta.url;
typeof import.meta.url;
```
```js title=Compiled
'file:///project/index.js';
'string';
```

### import.meta.main

Returns a boolean indicating whether the current module is the entry module.


```js title=Source
if (import.meta.main) {
  main();
}
```
```js title=Compiled
if (
  __webpack_module_cache__[/* entry module id */ __webpack_require__.s] ===
  module
) {
  main();
}
```

### import.meta.filename

Returns the full file path of the current module. This is the ESM equivalent of [`__filename`](#__filename), commonly used to get the current file's path information in ESM modules.

The compilation behavior is controlled by the [`node.__filename`](/config/node.md#node__filename) configuration option. See that configuration documentation for details.

### import.meta.dirname

Returns the directory path of the current module. This is the ESM equivalent of [`__dirname`](#__dirname), commonly used to construct paths based on the current file's location in ESM modules.

The compilation behavior is controlled by the [`node.__dirname`](/config/node.md#node__dirname) configuration option. See that configuration documentation for details.

### import.meta.resolve


[Added in v2.0.0](https://github.com/web-infra-dev/rspack/releases/tag/v2.0.0)

Stability: Experimental

The ESM equivalent of [`require.resolve()`](/api/runtime-api/module-methods.md#requireresolve), used to get the ID of another module. It includes the module in the final bundle and returns its module ID.


```js title=Source
let img = new Image();
img.src = import.meta.resolve('./img.png');
```
```js title=Compiled
let img = new Image();
img.src = './src/img.png'; // module ID of img.png
```

:::warning
`import.meta.resolve()` is currently experimental. To use it, you must enable [`module.parser.javascript.importMetaResolve`](/config/module-parser.md#javascriptimportmetaresolve). Rspack also plans to [align this API with the standard behavior](https://github.com/openjs-foundation/bundler-collab-space/issues/8) in the future, so its behavior may change. Use it with caution.
:::

### import.meta.glob


[Added in v2.0.5](https://github.com/web-infra-dev/rspack/releases/tag/v2.0.5)Rspack only

`import.meta.glob` allows you to import multiple modules at once using glob patterns. Rspack will parse and reference the matching modules during the build process.

- **Type:**

```ts
interface ImportMetaGlobOptions<Eager extends boolean = boolean> {
  /**
   * If `true`, modules are loaded synchronously.
   *
   * @default false
   */
  eager?: Eager;
  /**
   * Import only the specific named export. Set to `default` to import the default export.
   */
  import?: string;
  /**
   * Append a query to each matched module request.
   */
  query?: string | Record<string, string | number | boolean>;
  /**
   * Search files inside `node_modules` and hidden paths.
   *
   * @default false
   */
  exhaustive?: boolean;
  /**
   * Base path for resolving relative glob patterns and returned keys.
   */
  base?: string;
  /**
   * Match file paths case-sensitively.
   *
   * @default true
   */
  caseSensitive?: boolean;
}

function glob(
  /**
   * A glob pattern, or an array of glob patterns, to match files.
   */
  pattern: string | readonly string[],
  options?: ImportMetaGlobOptions<false>,
): Record<string, () => Promise<any>>;

function glob(
  /**
   * A glob pattern, or an array of glob patterns, to match files.
   */
  pattern: string | readonly string[],
  options: ImportMetaGlobOptions<true>,
): Record<string, any>;
```

- **Parameters:**
  - `pattern`: A glob pattern string, or an array of glob pattern strings, to match files (e.g., `'./dir/*.js'`). Supports `*`, `?`, `[abc]`, `{a,b}`, and `**` for recursive matching. Bare patterns can use `resolve.alias` (e.g., `'@/pages/*.js'`); for files inside the project root, returned keys use root-relative resolved paths. Array patterns can also include negative patterns such as `'!**/bar.js'`.
  - `options.eager`: When set to `true`, modules are included directly in the bundle and loaded synchronously. By default (`false`), modules are lazily loaded and each value is a thunk function that returns a `Promise` resolving to the module.
  - `options.import`: Import only the specified export from each matched module. For example, use `'default'` to get default exports, or a named export such as `'setup'`.
  - `options.query`: Append a query to each matched module request. It can be a query string such as `'?raw'`, or an object that is serialized as a URL query string. The keys returned from `import.meta.glob()` do not include the query.
  - `options.exhaustive`: Search files inside `node_modules` and hidden paths. This is disabled by default because it can increase build time.
  - `options.base`: Base path for resolving relative glob patterns and returned keys. Absolute glob patterns are still resolved from the project root, while returned keys are made relative to `base`.
  - `options.caseSensitive`: Whether to match file paths case-sensitively. When set to `false`, matching ignores case, while returned object keys preserve the filesystem's original casing. Defaults to `true`.

- **Example:**

```js
// Lazy (default): each value is a function () => Promise<module>
const modules = import.meta.glob('./dir/*.js');

// All matched modules are available as async thunks
const foo = await modules['./dir/foo.js']();
console.log(foo.default);

// Eager: each value is the module object directly
const eagerModules = import.meta.glob('./dir/*.js', { eager: true });
console.log(eagerModules['./dir/foo.js'].default);

// Import only the default export from each matched module
const defaultModules = import.meta.glob('./dir/*.js', { import: 'default' });
const fooDefault = await defaultModules['./dir/foo.js']();
console.log(fooDefault);

// Combine eager loading with import selection
const eagerDefaultModules = import.meta.glob('./dir/*.js', {
  eager: true,
  import: 'default',
});
console.log(eagerDefaultModules['./dir/foo.js']);

// Append a query to each matched import
const rawModules = import.meta.glob('./dir/*.js', {
  query: '?raw',
  import: 'default',
});
const rawFoo = await rawModules['./dir/foo.js']();

// Query objects are serialized as URL query strings
const dataModules = import.meta.glob('./dir/*.js', {
  query: { type: 'data', inline: true },
  eager: true,
});

// Resolve files from ./base and expose keys relative to ./base
const modulesWithBase = import.meta.glob('./**/*.js', {
  base: './base',
});

// Include matches inside node_modules and hidden paths
const exhaustiveModules = import.meta.glob(
  ['./node_modules/**/*.js', './.config/*.js'],
  {
    exhaustive: true,
  },
);

// Recursive matching with **
const allModules = import.meta.glob('./components/**/*.js', { eager: true });
```

:::tip
Rspack uses static analysis to parse the parameters of `import.meta.glob()` during compilation. Therefore, the `pattern` parameter must be a string literal or an array of string literals, and the `options` parameter must be an object literal. Variables or dynamically constructed values are not supported.
:::

:::warning
`import.meta.glob()` matches files on the filesystem at build time and includes them in the bundle. Avoid using overly broad glob patterns, as they can significantly increase build time and output size.
:::

### import.meta.webpackContext


Rspack/Webpack specific

`import.meta.webpackContext` is the ESM equivalent of [`require.context()`](/api/runtime-api/module-methods.md#requirecontext). It allows you to dynamically import a set of modules and is provided for compatibility with webpack context modules.

For new Rspack code, we recommend using [`import.meta.glob`](#importmetaglob) instead when webpack-compatible context behavior is not required.

You can use `import.meta.webpackContext` in your code, and Rspack will parse and reference the matching modules during the build process.

- **Type:**

```ts
function webpackContext(
  /**
   * A directory to search.
   */
  request: string,
  options?: {
    /**
     * Whether subdirectories should be searched.
     * @default true
     */
    recursive?: boolean;
    /**
     * A regular expression to match files.
     * @default /^\.\/.*$/ (any file)
     */
    regExp?: RegExp;
    /**
     * Module loading mode.
     * @default 'sync'
     */
    mode?: 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once';
    include?: RegExp;
    exclude?: RegExp;
    preload?: boolean | number;
    prefetch?: boolean | number;
    chunkName?: string;
    exports?: string | string[][];
  },
): Context;
```

- **Example:**

```js
// Create a context, with files from the test directory that
// can be required with a module specifier ending with `.test.js`.
const context = import.meta.webpackContext('./test', {
  recursive: false,
  regExp: /\.test\.js$/,
});
```

```js
// Create a context with all files in the parent folder and
// descending folders ending with `.stories.js`.
const context = import.meta.webpackContext('../', {
  recursive: true,
  regExp: /\.stories\.js$/,
});
```

```js
// If mode is set to 'lazy', the underlying modules will be loaded asynchronously
const context = import.meta.webpackContext('./locales', {
  recursive: true,
  regExp: /\.json$/,
  mode: 'lazy',
});
```

:::tip
Rspack uses static analysis to parse the parameters of `import.meta.webpackContext()` during compilation. Therefore, the parameters must be [literals](https://developer.mozilla.org/en-US/docs/Glossary/Literal).

For example, the value of `regExp` cannot be a variable, nor can it be the value generated by `new RegExp()`. It can only be a regular expression literal.
:::

#### context API

The context returned by `import.meta.webpackContext()` is a function that takes a `request` argument (module path).

This function has three properties: `resolve`, `keys`, and `id`.

- `resolve` is a function and returns the module id of the parsed module specifier.
- `keys` is a function that returns an array of all possible requests that the context module can handle.
- `id` is the module id of the context module. This may be useful for `module.hot.accept`.

This can be useful if you want to require all files in a directory or matching a pattern.

Consider a scenario where you have a folder structure like this:

```
src
├── components
│   ├── Button.js
│   ├── Header.js
│   └── Footer.js
```

You can use `import.meta.webpackContext()` to dynamically import all component files in the folder:

```js
const componentsContext = import.meta.webpackContext('./components', {
  recursive: false,
  regExp: /\.js$/,
});

componentsContext.keys().forEach((fileName) => {
  const componentModule = componentsContext(fileName);

  // Here you can use your module, for example console.log
  console.log(componentModule);
});
```

`import.meta.webpackContext()` streamlines the process of module importation especially when you have a lot of files to manage. When using it, please avoid matching unnecessary files, as this might lead to significantly increased build time and output size.

### import.meta.webpackHot


Rspack/Webpack specific

The ESM equivalent of [`module.hot`](#modulehot). `import.meta.webpackHot` can be used in strict ESM modules (module type `javascript/esm`), while `module.hot` cannot.

### import.meta.rspackHash


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

It provides access to the hash of the compilation.


```js title=Source
import.meta.rspackHash;
```
```js title=Compiled
__webpack_require__.h();

// webpack/runtime/get_full_hash
__webpack_require__.h = function () {
  return '9210c6f859a51c6f9a62';
};
```

### import.meta.rspackPublicPath


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

Equals the configuration option's [`output.publicPath`](/config/output.md#outputpublicpath).


```js title=Source
import.meta.rspackPublicPath;
```
```js title=Compiled
__webpack_require__.p;

// output.publicPath !== "auto"
__webpack_require__.p = 'output.publicPath';
// output.publicPath === "auto"
__webpack_require__.p = 'calculated from document/location';
```

> See [Dynamically set publicPath](/guide/features/asset-base-path.md#dynamically-set-publicpath) for more information about the usage of `import.meta.rspackPublicPath`.

### import.meta.rspackBaseUri


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

Get or change base URI at runtime.


```js title=Source
import.meta.rspackBaseUri;
```
```js title=Compiled
__webpack_require__.b;

// chunk loading
__webpack_require__.b = document.baseURI || self.location.href;
```

### import.meta.rspackNonce


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

Rspack is capable of adding a nonce to all scripts that it loads. To activate this feature, set `import.meta.rspackNonce` in your entry script.


```js title=Source
import.meta.rspackNonce = 'your_nonce_code';
```
```js title=Compiled
__webpack_require__.nc = '2312312';

// webpack/runtime/load_script
if (__webpack_require__.nc) {
  script.setAttribute('nonce', __webpack_require__.nc);
}
```

### import.meta.rspackShareScopes


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

This object is used as a shared scope in the remote container and is filled with the provided modules from a host.


```js title=Source
import.meta.rspackShareScopes;
```
```js title=Compiled
__webpack_require__.S;
```

### import.meta.rspackInitSharing


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

This method is used to initialize modules of a shared scope in the host container.


```js title=Source
import.meta.rspackInitSharing('default');
```
```js title=Compiled
__webpack_require__.I('default');
```

### import.meta.rspackVersion


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

Current Rspack version, default to version in `@rspack/core/package.json`, can be modified through `output.bundlerInfo.version`.


```js title=Source
import.meta.rspackVersion;
```
```js title=Compiled
__webpack_require__.rv();

// webpack/runtime/rspack_version
__webpack_require__.rv = () => '0.7.4';
```

### import.meta.rspackUniqueId


[Added in v2.1.2](https://github.com/web-infra-dev/rspack/releases/tag/v2.1.2)Rspack only

The ID of the current bundler, the value is `bundler={bundler}@{version}`:

- `bundler`: Default to `"rspack"` and can be modified through [output.bundlerInfo.bundler](/config/output.md#outputbundlerinfo).
- `version`: Default to version in `@rspack/core/package.json` and can be modified through [output.bundlerInfo.version](/config/output.md#outputbundlerinfo).


```js title=Source
import.meta.rspackUniqueId;
```
```js title=Compiled
__webpack_require__.ruid;

// webpack/runtime/rspack_unique_id
__webpack_require__.ruid = 'bundler=rspack@2.1.2';
```

## Runtime

### \_\_webpack\_hash\_\_


Stability: Deprecated

Rspack/Webpack specific

The CommonJS equivalent of [`import.meta.rspackHash`](#importmetarspackhash).

### \_\_webpack\_runtime\_id\_\_


Rspack/Webpack specific

Access the runtime id of current entry.


```js title=Source
__webpack_runtime_id__
```
```js title=Compiled
__webpack_require__.j;

// webpack/runtime/runtime_id
__webpack_require__.j = '909';
```

### \_\_webpack\_public\_path\_\_


Stability: Deprecated

Rspack/Webpack specific

The CommonJS equivalent of [`import.meta.rspackPublicPath`](#importmetarspackpublicpath).

### \_\_webpack\_base\_uri\_\_


Stability: Deprecated

Rspack/Webpack specific

The CommonJS equivalent of [`import.meta.rspackBaseUri`](#importmetarspackbaseuri).

### \_\_webpack\_nonce\_\_


Stability: Deprecated

Rspack/Webpack specific

The CommonJS equivalent of [`import.meta.rspackNonce`](#importmetarspacknonce).

## Modules

### \_\_webpack\_modules\_\_


Rspack/Webpack specific

Access to the internal object of all modules.


```js title=Source
__webpack_modules__
```
```js title=Compiled
var __webpack_modules__ = {
  'main.js': function () {
    __webpack_require__.m;
  },
};
__webpack_require__.m = __webpack_modules__;
```

### \_\_webpack\_module\_\_


Rspack/Webpack specific

It provides access to the current `module`. `module` is not available in strict ESM.


```js title=Source
__webpack_module__
```
```js title=Compiled
"main.js": function(renamed_module) {
  renamed_module
}
```

### \_\_webpack\_module\_\_.id


Rspack/Webpack specific

It provides access to the ID of current module (`module.id`). `module` is not available in strict ESM.


```js title=Source
__webpack_module__.id
```
```js title=Compiled
"main.js": function(renamed_module) {
  renamed_module.id
}
```

### \_\_webpack\_layer\_\_


Rspack/Webpack specific

Access the [layer](/guide/advanced/layer.md) of the current module. Its value is the configured layer name, or `null` when the module has no layer.

Rspack replaces `__webpack_layer__` at compile time, allowing optimizers to remove unreachable layer-specific branches.


```js title=Source
const currentLayer = __webpack_layer__;
```
```js title=Compiled
const currentLayer = 'client';
```

### \_\_webpack\_require\_\_


Rspack/Webpack specific

The raw require function.
This expression isn't parsed by the Parser for dependencies.


```js title=Source
__webpack_require__('./dep.js')
```
```js title=Compiled
"main.js": function(_, __, renamed_require) {
  renamed_require('./dep.js')
}
```

### \_\_non\_webpack\_require\_\_


Rspack/Webpack specific

Generates a `require` function that is not parsed by webpack.
Can be used to do cool stuff with a global require function if available.


```js title=Source
__non_webpack_require__('outer.js')
```
```js title=Compiled
"main.js": function(_, __, __webpack_require__) {
  require('outer.js')
}
```

### \_\_webpack\_is\_included\_\_


Rspack/Webpack specific

Test whether or not the given module is bundled by webpack.


```js title=Source
if (__webpack_is_included__('./dep.js')) {
  // do something
}
```
```js title=Compiled
if (true) {
  // do something
}
```

### \_\_resourceQuery


Rspack/Webpack specific

The resource query of the current module.
If the following `require` call was made, then the query string would be available in `file.js`.

```js
require('file.js?test');
```


```js title=Source
__resourceQuery
```
```js title=Compiled
'?test';
```

### \_\_webpack\_exports\_info\_\_


Rspack/Webpack specific

In modules, `__webpack_exports_info__` is available to allow exports introspection:

- `__webpack_exports_info__` is always `true`
- `__webpack_exports_info__.<exportName>.used` is `false` when the export is known to be unused, `true` otherwise
- `__webpack_exports_info__.<exportName>.useInfo` is
  - `false` when the export is known to be unused
  - `true` when the export is known to be used
  - `null` when the export usage could depend on runtime conditions
  - `undefined` when no info is available
- `__webpack_exports_info__.<exportName>.provideInfo` is
  - `false` when the export is known to be not provided
  - `true` when the export is known to be provided
  - `null` when the export provision could depend on runtime conditions
  - `undefined` when no info is available
- Accessing the info from nested exports is possible: i. e. `__webpack_exports_info__.<exportName>.<exportProperty1>.<exportProperty2>.used`
- Check whether exports can be mangled with `__webpack_exports_info__.<exportName>.canMangle`


```js title=Source
if (__webpack_exports_info__.someUsedExport.used) { }
if (__webpack_exports_info__.someUnusedExport.used) { }
```
```js title=Compiled
if (true) {
}
if (false) {
}
```

## Chunks

### \_\_webpack\_chunkname\_\_


Rspack/Webpack specific

Get current chunk name.


```js title=Source
__webpack_chunkname__
```
```js title=Compiled
__webpack_require__.cn;

// webpack/runtime/chunk_name
__webpack_require__.cn = 'main';
```

### \_\_webpack\_chunk\_load\_\_


Rspack/Webpack specific

The internal chunk loading function. Takes one argument:

- `chunkId`: the id for the chunk to load.


```js title=Source
__webpack_chunk_load__
```
```js title=Compiled
__webpack_require__.e;

// webpack/runtime/ensure_chunk
__webpack_require__.e = function (chunkId) {
  // return chunk loading promise
};
```

Example to load chunks from alternate public path when one failed:

```js
const originalLoad = __webpack_chunk_load__;
const publicPaths = ['a', 'b', 'c'];
__webpack_chunk_load__ = async (id) => {
  let error;
  for (const path of publicPaths) {
    import.meta.rspackPublicPath = path;
    try {
      return await originalLoad(id);
    } catch (e) {
      error = e;
    }
  }
  throw error;
};
import('./module-a').then((moduleA) => {
  // now webpack will use the custom __webpack_chunk_load__ to load chunk
});
```

### \_\_webpack\_get\_script\_filename\_\_


Rspack/Webpack specific

It provides filename of the chunk by its id.


```js title=Source
__webpack_get_script_filename__
```
```js title=Compiled
__webpack_require__.u;

// webpack/runtime/get_chunk_filename
__webpack_require__.u = function (chunkId) {
  // ...
};
```

It is assignable, which allows changing the filename used by the runtime. For example, it can be used to determine the final path when loading chunks.

```js
const oldFn = __webpack_get_script_filename__;

__webpack_get_script_filename__ = (chunkId) => {
  const filename = oldFn(chunkId);
  return filename + '.changed';
};
```

## Module Federation

### \_\_webpack\_share\_scopes\_\_


Stability: Deprecated

Rspack/Webpack specific

The CommonJS equivalent of [`import.meta.rspackShareScopes`](#importmetarspacksharescopes).

### \_\_webpack\_init\_sharing\_\_


Stability: Deprecated

Rspack/Webpack specific

The CommonJS equivalent of [`import.meta.rspackInitSharing`](#importmetarspackinitsharing).

## System.js

### \_\_system\_context\_\_


Rspack/Webpack specific

Context from System.js when `output.library.type="system"`

## Rspack

### \_\_rspack\_version\_\_


Stability: Deprecated

Rspack only

The CommonJS equivalent of [`import.meta.rspackVersion`](#importmetarspackversion).

### \_\_rspack\_unique\_id\_\_


Stability: Deprecated

Rspack only

The CommonJS equivalent of [`import.meta.rspackUniqueId`](#importmetarspackuniqueid).


This page is adapted from [webpack documentation](https://webpack.js.org/api/module-variables/) under the [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), with modifications.

