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
__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
// Set before importing any modules
__webpack_public_path__ = '/assets/';
// Now all assets will be loaded from /assets/
import('./module.js');
CDN Configuration
// 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
// 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
// Use current origin + path
__webpack_public_path__ = window.location.origin + '/static/';
Set __webpack_public_path__ in your entry point before importing any other modules. Changes after modules are loaded won’t affect already-loaded assets.
webpack_base_uri
Sets the base URI for WebAssembly and Worker module resolution.
Type
__webpack_base_uri__: string
Description
Controls the base URI used for resolving WebAssembly modules and Web Workers. Defaults to document.baseURI.
Usage Examples
// 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
__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
// 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`);
});
Direct manipulation of __webpack_modules__ is not recommended. This API is primarily for debugging and advanced use cases.
webpack_chunk_load
Function to load chunks programmatically.
Type
__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
// 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
__webpack_module__.id: string | number
Description
Provides the unique identifier for the current module.
Usage Examples
// 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
Description
Provides the hash of the current compilation. Useful for cache busting and version tracking.
Usage Examples
// 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__}`);
__webpack_hash__ remains constant for a given build. It changes only when you rebuild with webpack.
webpack_chunkname
The name of the current chunk.
Type
__webpack_chunkname__: string
Description
Provides the name of the chunk containing the current module.
Usage Examples
// 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
__webpack_get_script_filename__(chunkId: string | number): string
Description
Returns the filename that would be used for a given chunk ID.
Usage Examples
// 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
__webpack_nonce__: string
Description
Configures the nonce attribute for all script and style tags created by webpack. Used for Content Security Policy.
Usage Examples
// 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
// 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
__webpack_runtime_id__: string
Description
Identifies the current runtime when using multiple runtimes.
Usage Examples
// 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
__webpack_layer__: string | null
Description
Provides the layer name when using webpack’s experimental layers feature.
Usage Examples
// 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
__webpack_share_scopes__: Record<string, ShareScope>
Description
Provides access to shared module scopes when using Module Federation.
Usage Examples
// 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
__webpack_init_sharing__(scope: string): Promise<void>
Description
Initializes a share scope for Module Federation.
Usage Examples
// 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
__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
// 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);
__non_webpack_require__ is only available when targeting Node.js environments. Using it in browser builds will cause errors.
system_context
SystemJS context object.
Type
__system_context__: System.Context
Description
Provides the SystemJS context when using SystemJS output format.
Usage Examples
// 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
// 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
// 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
// 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:
// 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