Back to Rspack

Module variables

website/docs/en/api/runtime-api/module-variables.mdx

2.0.118.4 KB
Original Source

import WebpackLicense from '@components/WebpackLicense'; import Columns from '@components/Columns'; import { ApiMeta, Stability } from '@components/ApiMeta';

<WebpackLicense from="https://webpack.js.org/api/module-variables/" />

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
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 for details.

global

See node.js global for details.

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

<Columns> ```js title=Source global['property'] ```
js
__webpack_require__.g['property'];

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

__filename

Depends on the configuration node.__filename.

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

<Columns> ```js title=Source __filename ```
js
'src/main.js';
</Columns>

__dirname

Depends on the configuration node.__dirname.

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

<Columns> ```js title=Source __dirname ```
js
'src';
</Columns>

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 is javascript/auto or javascript/esm).

Normally, unknown import.meta metadata is replaced with undefined by default. When using ESM output, module.parser.javascript.importMeta defaults to 'preserve-unknown', so unknown metadata is preserved for runtime evaluation.

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.

<Columns>
js
// 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
// Warning
Object.keys({});

('object');

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

let { url } = { url: 'file:///project/index.js' };
</Columns>

import.meta.url

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

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

import.meta.main

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

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

import.meta.filename

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

The compilation behavior is controlled by the 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, commonly used to construct paths based on the current file's location in ESM modules.

The compilation behavior is controlled by the node.__dirname configuration option. See that configuration documentation for details.

import.meta.resolve

<ApiMeta stability={Stability.Experimental} addedVersion="2.0.0" />

The ESM equivalent of require.resolve(), used to get the ID of another module. It includes the module in the final bundle and returns its module ID.

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

:::warning import.meta.resolve() is currently experimental. To use it, you must enable module.parser.javascript.importMetaResolve. Rspack also plans to align this API with the standard behavior in the future, so its behavior may change. Use it with caution. :::

import.meta.webpackContext

<ApiMeta specific={['Rspack', 'Webpack']} />

import.meta.webpackContext is the ESM equivalent of require.context(). It allows you to dynamically import a set of modules.

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.

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

<ApiMeta specific={['Rspack', 'Webpack']} />

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

Runtime

__webpack_hash__

<ApiMeta specific={['Rspack', 'Webpack']} />

It provides access to the hash of the compilation.

<Columns> ```js title=Source __webpack_hash__ ```
js
__webpack_require__.h();

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

__webpack_runtime_id__

<ApiMeta specific={['Rspack', 'Webpack']} />

Access the runtime id of current entry.

<Columns> ```js title=Source __webpack_runtime_id__ ```
js
__webpack_require__.j;

// webpack/runtime/runtime_id
__webpack_require__.j = '909';
</Columns>

__webpack_public_path__

<ApiMeta specific={['Rspack', 'Webpack']} />

Equals the configuration option's output.publicPath.

<Columns> ```js title=Source __webpack_public_path__ ```
js
__webpack_require__.p;

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

See Dynamically set publicPath for more information about the usage of __webpack_public_path__.

__webpack_base_uri__

<ApiMeta specific={['Rspack', 'Webpack']} />

Get or change base URI at runtime.

<Columns> ```js title=Source __webpack_base_uri__ ```
js
__webpack_require__.b;

// chunk loading
__webpack_require__.b = document.baseURI || self.location.href;
</Columns>

__webpack_nonce__

<ApiMeta specific={['Rspack', 'Webpack']} />

Rspack is capable of adding a nonce to all scripts that it loads. To activate this feature, set a __webpack_nonce__ variable and include it in your entry script.

<Columns> ```js title=Source __webpack_nonce__ = 'your_nonce_code'; ```
js
__webpack_require__.nc = '2312312';

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

Modules

__webpack_modules__

<ApiMeta specific={['Rspack', 'Webpack']} />

Access to the internal object of all modules.

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

__webpack_module__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

<Columns> ```js title=Source __webpack_module__ ```
js
"main.js": function(renamed_module) {
  renamed_module
}
</Columns>

__webpack_module__.id

<ApiMeta specific={['Rspack', 'Webpack']} />

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

<Columns> ```js title=Source __webpack_module__.id ```
js
"main.js": function(renamed_module) {
  renamed_module.id
}
</Columns>

__webpack_require__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

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

__non_webpack_require__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

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

__webpack_is_included__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

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

__resourceQuery

<ApiMeta specific={['Rspack', 'Webpack']} />

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');
<Columns> ```js title=Source __resourceQuery ```
js
'?test';
</Columns>

__webpack_exports_info__

<ApiMeta addedVersion="1.0.0" specific={['Rspack', 'Webpack']} />

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
<Columns> ```js title=Source if (__webpack_exports_info__.someUsedExport.used) { } if (__webpack_exports_info__.someUnusedExport.used) { } ```
js
if (true) {
}
if (false) {
}
</Columns>

Chunks

__webpack_chunkname__

<ApiMeta specific={['Rspack', 'Webpack']} />

Get current chunk name.

<Columns> ```js title=Source __webpack_chunkname__ ```
js
__webpack_require__.cn;

// webpack/runtime/chunk_name
__webpack_require__.cn = 'main';
</Columns>

__webpack_chunk_load__

<ApiMeta specific={['Rspack', 'Webpack']} />

The internal chunk loading function. Takes one argument:

  • chunkId: the id for the chunk to load.
<Columns> ```js title=Source __webpack_chunk_load__ ```
js
__webpack_require__.e;

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

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) {
    __webpack_public_path__ = 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__

<ApiMeta addedVersion="1.0.0" specific={['Rspack', 'Webpack']} />

It provides filename of the chunk by its id.

<Columns> ```js title=Source __webpack_get_script_filename__ ```
js
__webpack_require__.u;

// webpack/runtime/get_chunk_filename
__webpack_require__.u = function (chunkId) {
  // ...
};
</Columns>

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__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

__webpack_init_sharing__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

System.js

__system_context__

<ApiMeta specific={['Rspack', 'Webpack']} />

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

Rspack

__rspack_version__

<ApiMeta specific={['Rspack']} /> Current Rspack version, default to version in @rspack/core/package.json, can be modified through output.bundlerInfo.version.

<Columns> ```js title=Source __rspack_version__ ```
js
__webpack_require__.rv;

// webpack/runtime/rspack_version
__webpack_require__.rv = '0.7.4';
</Columns>

__rspack_unique_id__

<ApiMeta addedVersion="1.0.0" specific={['Rspack']} />

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

<Columns> ```js title=Source __rspack_unique_id__ ```
js
__webpack_require__.ruid;

// webpack/runtime/rspack_unique_id
__webpack_require__.ruid = '[email protected]';
</Columns>