> ## Documentation Index
> Fetch the complete documentation index at: https://docs.webpack.js.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Module Variables

> Special webpack module variables for runtime configuration and metadata

Webpack provides several special variables that can be used in your modules for runtime configuration, metadata access, and module information.

## **webpack\_public\_path**

Configures the public path for webpack assets at runtime.

### Type

```typescript theme={null}
__webpack_public_path__: string
```

### Description

Controls the base path for all assets (chunks, images, fonts) emitted by webpack. Can be set dynamically at runtime before importing modules.

### Usage Examples

#### Basic Assignment

```javascript theme={null}
// Set before importing any modules
__webpack_public_path__ = '/assets/';

// Now all assets will be loaded from /assets/
import('./module.js');
```

#### CDN Configuration

```javascript theme={null}
// Load assets from CDN
__webpack_public_path__ = 'https://cdn.example.com/assets/';

// Dynamic CDN selection
if (process.env.NODE_ENV === 'production') {
  __webpack_public_path__ = 'https://cdn.example.com/';
} else {
  __webpack_public_path__ = '/dev-assets/';
}
```

#### Runtime Detection

```javascript theme={null}
// Determine public path from script tag
const scriptSrc = document.currentScript?.src;
if (scriptSrc) {
  __webpack_public_path__ = scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);
}
```

#### Relative to Current Origin

```javascript theme={null}
// Use current origin + path
__webpack_public_path__ = window.location.origin + '/static/';
```

<Note>
  Set `__webpack_public_path__` in your entry point before importing any other modules. Changes after modules are loaded won't affect already-loaded assets.
</Note>

***

## **webpack\_base\_uri**

Sets the base URI for WebAssembly and Worker module resolution.

### Type

```typescript theme={null}
__webpack_base_uri__: string
```

### Description

Controls the base URI used for resolving WebAssembly modules and Web Workers. Defaults to `document.baseURI`.

### Usage Examples

```javascript theme={null}
// Set custom base URI
__webpack_base_uri__ = 'https://wasm.example.com/';

// Load WASM module
import('./fibonacci.wasm');
```

***

## **webpack\_modules**

Access to webpack's internal module registry.

### Type

```typescript theme={null}
__webpack_modules__: Record<string | number, Module>
```

### Description

Provides access to all loaded modules. Each module is a function that executes the module code.

### Usage Examples

```javascript theme={null}
// Access module registry
console.log(__webpack_modules__);

// Check if module is loaded
const moduleId = 42;
if (__webpack_modules__[moduleId]) {
  console.log('Module loaded');
}

// Iterate over all modules
Object.keys(__webpack_modules__).forEach(id => {
  console.log(`Module ${id} is available`);
});
```

<Warning>
  Direct manipulation of `__webpack_modules__` is not recommended. This API is primarily for debugging and advanced use cases.
</Warning>

***

## **webpack\_chunk\_load**

Function to load chunks programmatically.

### Type

```typescript theme={null}
__webpack_chunk_load__(chunkId: string | number): Promise<void>
```

### Description

Manually load a specific chunk. Returns a Promise that resolves when the chunk is loaded.

### Usage Examples

```javascript theme={null}
// Preload a chunk
await __webpack_chunk_load__('vendors');

// Load multiple chunks
await Promise.all([
  __webpack_chunk_load__('chunk-1'),
  __webpack_chunk_load__('chunk-2'),
  __webpack_chunk_load__('chunk-3')
]);
```

***

## **webpack\_module**.id

The module ID of the current module.

### Type

```typescript theme={null}
__webpack_module__.id: string | number
```

### Description

Provides the unique identifier for the current module.

### Usage Examples

```javascript theme={null}
// Log current module ID
console.log('Current module ID:', __webpack_module__.id);

// Use in module registry
const currentModule = __webpack_modules__[__webpack_module__.id];
```

***

## **webpack\_hash**

The compilation hash at runtime.

### Type

```typescript theme={null}
__webpack_hash__: string
```

### Description

Provides the hash of the current compilation. Useful for cache busting and version tracking.

### Usage Examples

```javascript theme={null}
// Display build version
console.log('Build hash:', __webpack_hash__);

// Cache key
const cacheKey = `app-cache-${__webpack_hash__}`;
localStorage.setItem(cacheKey, data);

// API versioning
fetch(`/api/data?v=${__webpack_hash__}`);
```

<Note>
  `__webpack_hash__` remains constant for a given build. It changes only when you rebuild with webpack.
</Note>

***

## **webpack\_chunkname**

The name of the current chunk.

### Type

```typescript theme={null}
__webpack_chunkname__: string
```

### Description

Provides the name of the chunk containing the current module.

### Usage Examples

```javascript theme={null}
// Log chunk name
console.log('Running in chunk:', __webpack_chunkname__);

// Conditional logic based on chunk
if (__webpack_chunkname__ === 'main') {
  initializeApp();
}
```

***

## **webpack\_get\_script\_filename**

Function to get the filename for a chunk ID.

### Type

```typescript theme={null}
__webpack_get_script_filename__(chunkId: string | number): string
```

### Description

Returns the filename that would be used for a given chunk ID.

### Usage Examples

```javascript theme={null}
// Get chunk filename
const filename = __webpack_get_script_filename__('vendors');
console.log(filename); // 'vendors.1234abcd.js'

// Preload hint
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'script';
link.href = __webpack_get_script_filename__('critical-feature');
document.head.appendChild(link);
```

***

## **webpack\_nonce**

Sets the nonce for script tags (Content Security Policy).

### Type

```typescript theme={null}
__webpack_nonce__: string
```

### Description

Configures the `nonce` attribute for all script and style tags created by webpack. Used for Content Security Policy.

### Usage Examples

```javascript theme={null}
// Set nonce before loading modules
__webpack_nonce__ = 'c29tZSBjb29sIHN0cmluZyB3aWxsIHBvcCB1cCAxMjM=';

// All dynamically created scripts will include this nonce
import('./module.js');
// Creates: <script nonce="c29tZS..." src="module.js"></script>
```

#### Server-Side Integration

```javascript theme={null}
// Express middleware
app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
  next();
});

// In HTML template
<script>
  __webpack_nonce__ = '<%= cspNonce %>';
</script>
<script src="/main.js"></script>
```

***

## **webpack\_runtime\_id**

The runtime ID for the current runtime.

### Type

```typescript theme={null}
__webpack_runtime_id__: string
```

### Description

Identifies the current runtime when using multiple runtimes.

### Usage Examples

```javascript theme={null}
// Check runtime context
console.log('Runtime ID:', __webpack_runtime_id__);

if (__webpack_runtime_id__ === 'main-runtime') {
  // Main runtime logic
} else {
  // Secondary runtime logic
}
```

***

## **webpack\_layer**

The layer name of the current module.

### Type

```typescript theme={null}
__webpack_layer__: string | null
```

### Description

Provides the layer name when using webpack's experimental layers feature.

### Usage Examples

```javascript theme={null}
// Check current layer
if (__webpack_layer__ === 'client') {
  // Client-side code
} else if (__webpack_layer__ === 'server') {
  // Server-side code
}
```

***

## **webpack\_share\_scopes**

Access to module federation share scopes.

### Type

```typescript theme={null}
__webpack_share_scopes__: Record<string, ShareScope>
```

### Description

Provides access to shared module scopes when using Module Federation.

### Usage Examples

```javascript theme={null}
// Access shared dependencies
const defaultScope = __webpack_share_scopes__.default;

// Check if module is shared
if (__webpack_share_scopes__.default?.['react']) {
  console.log('React is shared');
}
```

***

## **webpack\_init\_sharing**

Initialize module federation sharing.

### Type

```typescript theme={null}
__webpack_init_sharing__(scope: string): Promise<void>
```

### Description

Initializes a share scope for Module Federation.

### Usage Examples

```javascript theme={null}
// Initialize default share scope
await __webpack_init_sharing__('default');

// Now shared modules are available
const container = await import('remote/App');
```

***

## **non\_webpack\_require**

Native Node.js require (bypasses webpack).

### Type

```typescript theme={null}
__non_webpack_require__: NodeRequire
```

### Description

Provides access to Node.js's native `require` function, bypassing webpack's module system. Only available in Node.js targets.

### Usage Examples

```javascript theme={null}
// Load native Node.js module
const fs = __non_webpack_require__('fs');

// Load module from absolute path
const config = __non_webpack_require__('/etc/app/config.json');

// Dynamic native require
const moduleName = 'path';
const nativeModule = __non_webpack_require__(moduleName);
```

<Warning>
  `__non_webpack_require__` is only available when targeting Node.js environments. Using it in browser builds will cause errors.
</Warning>

***

## **system\_context**

SystemJS context object.

### Type

```typescript theme={null}
__system_context__: System.Context
```

### Description

Provides the SystemJS context when using SystemJS output format.

### Usage Examples

```javascript theme={null}
// Access SystemJS context
console.log(__system_context__.import);

// Use SystemJS features
__system_context__.import('./module.js').then(module => {
  console.log(module);
});
```

***

## Common Patterns

### Dynamic Public Path Configuration

```javascript theme={null}
// config.js
(function() {
  // Detect environment
  const isDev = process.env.NODE_ENV === 'development';
  const isStaging = window.location.hostname.includes('staging');
  
  // Set public path
  if (isDev) {
    __webpack_public_path__ = '/assets/';
  } else if (isStaging) {
    __webpack_public_path__ = 'https://staging-cdn.example.com/';
  } else {
    __webpack_public_path__ = 'https://cdn.example.com/';
  }
  
  // Log for debugging
  console.log('Public path:', __webpack_public_path__);
})();
```

### CSP Nonce Setup

```javascript theme={null}
// entry.js
// Extract nonce from meta tag
const metaNonce = document.querySelector('meta[property="csp-nonce"]');
if (metaNonce) {
  __webpack_nonce__ = metaNonce.getAttribute('content');
}

// Now safe to load modules
import('./app.js');
```

### Module Hot Reload with Hash

```javascript theme={null}
// Display version in footer
const versionEl = document.getElementById('version');
if (versionEl) {
  versionEl.textContent = `v${__webpack_hash__}`;
}

// Clear old cache on new deploy
const CURRENT_CACHE = `app-v${__webpack_hash__}`;
const cacheNames = await caches.keys();
await Promise.all(
  cacheNames
    .filter(name => name !== CURRENT_CACHE)
    .map(name => caches.delete(name))
);
```

***

## TypeScript Declarations

Add these declarations to your TypeScript project:

```typescript theme={null}
// globals.d.ts
declare let __webpack_public_path__: string;
declare let __webpack_base_uri__: string;
declare const __webpack_modules__: Record<string | number, any>;
declare const __webpack_chunk_load__: (chunkId: string | number) => Promise<void>;
declare const __webpack_module__: { id: string | number };
declare const __webpack_hash__: string;
declare const __webpack_chunkname__: string;
declare const __webpack_get_script_filename__: (chunkId: string | number) => string;
declare let __webpack_nonce__: string;
declare const __webpack_runtime_id__: string;
declare const __webpack_layer__: string | null;
declare const __webpack_share_scopes__: Record<string, any>;
declare const __webpack_init_sharing__: (scope: string) => Promise<void>;
declare const __non_webpack_require__: NodeRequire;
declare const __system_context__: any;
```

***

## See Also

* [import()](/api/module-methods/import) - Dynamic imports
* [require()](/api/module-methods/require) - CommonJS require
* [Public Path](/configuration/output) - Configuring public path
* [Module Federation](/guides/module-federation) - Module federation guide
