CC 4.0 License

The content of this section is derived from the content of the following links and is subject to the CC BY 4.0 license.

The following contents can be assumed to be the result of modifications and deletions based on the original contents if not specifically stated.

Module Methods

This section covers all methods available in code compiled with Rspack. When using Rspack to bundle your application, you can pick from a variety of module syntax styles including ES6, CommonJS.

While Rspack supports multiple module syntaxes, we recommend following a single syntax for consistency and to avoid odd behaviors/bugs.

Actually Rspack would enforce the recommendation for .mjs files, .cjs files or .js files when their nearest parent package.json file contains a "type" field with a value of either "module" or "commonjs". Please pay attention to these enforcements before you read on

  • .mjs or .js with "type": "module" in package.json
    • No CommonJS allowed, for example, you can't use require, module.exports or exports
    • File extensions are required when importing, e.g, you should use import './src/App.mjs' instead of import './src/App' (you can disable this enforcement with Rule.resolve.fullySpecified)
  • .cjs or .js with "type": "commonjs" in package.json
    • Neither import nor export is available

Rspack support ES6 module syntax natively, you can use static import, export and import() syntax.

WARNING

Keep in mind that you will still probably need SWC or Babel for other ES6+ features.

import

Statically import the exports of another module.

import MyModule from './my-module.js';
import { NamedExport } from './other-module.js';

You can also import Data URI

import 'data:text/javascript;charset=utf-8;base64,Y29uc29sZS5sb2coJ2lubGluZSAxJyk7';
import {
  number,
  fn,
} from 'data:text/javascript;charset=utf-8;base64,ZXhwb3J0IGNvbnN0IG51bWJlciA9IDQyOwpleHBvcnQgY29uc3QgZm4gPSAoKSA9PiAiSGVsbG8gd29ybGQiOw==';

export

Export anything as a default or named export.

// Named exports
export var Count = 5;
export function Multiply(a, b) {
  return a * b;
}

// Default export
export default {
  // Some data...
};

Dynamic import()

function import(path: string): Promise;

Dynamically load modules. Calls to import() are treated as split points, meaning the requested module and its children are split out into a separate chunk.

if (module.hot) {
  import('lodash').then(_ => {
    // Do something with lodash (a.k.a '_')...
  });
}
WARNING

This feature relies on Promise internally. If you use import() with older browsers, remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

Dynamic expressions in import()

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included. For example, import(./locale/${language}.json) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

// imagine we had a method to get language from cookies or other storage
const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then(module => {
  // do something with the translations
});

Magic Comments

Rspack/Webpack specific

Inline comments to make features work. By adding comments to the import, we can do things such as name our chunk or select different modes. For a full list of these magic comments see the code below followed by an explanation of what these comments do.

// Single target
import(
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  /* webpackExports: ["default", "named"] */
  /* webpackFetchPriority: "high" */
  'module'
);

// Multiple possible targets
import(
  /* webpackInclude: /\.json$/ */
  /* webpackExclude: /\.noimport\.json$/ */
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  /* webpackPreload: true */
  `./locale/${language}`
);
webpackIgnore
  • Type: boolean

Disables dynamic import parsing when set to true.

WARNING

Note that setting webpackIgnore to true opts out of code splitting.

webpackMode
  • Type: "eager" | "lazy" | "weak" | "lazy-once"

Different modes for resolving dynamic imports can be specified. The following options are supported

  • 'lazy' (default): Generates a lazy-loadable chunk for each import()ed module.
  • 'lazy-once': Generates a single lazy-loadable chunk that can satisfy all calls to import(). The chunk will be fetched on the first call to import(), and subsequent calls to import() will use the same network response. Note that this only makes sense in the case of a partially dynamic statement, e.g. import("./locales/${language}.json"), where multiple module paths that can potentially be requested.
  • 'eager': Generates no extra chunk. All modules are included in the current chunk and no additional network requests are made. A Promise is still returned but is already resolved. In contrast to a static import, the module isn't executed until the call to import() is made.
  • 'weak': Tries to load the module if the module function has already been loaded in some other way (e.g. another chunk imported it or a script containing the module was loaded). A Promise is still returned, but only successfully resolves if the chunks are already on the client. If the module is not available, the Promise is rejected. A network request will never be performed. This is useful for universal rendering when required chunks are always manually served in initial requests (embedded within the page), but not in cases where app navigation will trigger an import not initially served.
webpackPrefetch
  • Type
    • number: chunk prefetch priority
    • boolean: false means not to prefetch, true means priority is 0

Tells the browser that the resource is probably needed for some navigation in the future, see Prefetching/Preloading modules for more details.

webpackPreload
  • Type
    • number: chunk preload priority
    • boolean: false means not to preload, true means priority is 0

Tells the browser that the resource might be needed during the current navigation, , see Prefetching/Preloading modules for more details.

webpackChunkName
  • Type:: string

A name for the new chunk.

webpackFetchPriority
  • Type:: "low" | "high" | "auto"

Set fetchPriority for specific dynamic imports. It's also possible to set a global default value for all dynamic imports by using the module.parser.javascript.dynamicImportFetchPriority option.

webpackInclude
  • Type:: Regexp

A regular expression that will be matched against during import resolution. Only modules that match will be bundled.

webpackExclude
  • Type:: Regexp

A regular expression that will be matched against during import resolution. Any module that matches will not be bundled.

INFO

Note that webpackInclude and webpackExclude options do not interfere with the prefix. eg: ./locale.

webpackExports
  • 型:: string | string[]

動的にimport()されたモジュールの指定されたエクスポートのみをバンドルするようにwebpackに指示します。これにより、チャンクの出力サイズを削減できます。

CommonJS

RspackはCommonJS構文もネイティブにサポートしています。requiremodule.exportsメソッドを使用できます。

require

別のモジュールからエクスポートを同期的に取得します。

require(dependency: string);

require.resolve

モジュールのIDを同期的に取得します。require.cache[id]または__webpack_require__(id)(このような使用方法を避けるのが最適です)でのみ使用できる不透明な値として扱うことをお勧めします。

require.resolve(dependency: string);
WARNING

モジュールIDの型は、optimization.moduleIds設定に応じて数値または文字列になります。

require.cache

同じモジュールを複数回requireしても、モジュールの実行は1回のみ、エクスポートも1回のみです。そのため、ランタイムにキャッシュが存在します。このキャッシュから値を削除すると、モジュールが新しく実行され、新しいエクスポートが生成されます。

var d1 = require('dependency');
require('dependency') === d1;
delete require.cache[require.resolve('dependency')];
require('dependency') !== d1;

require.context

Rspack/Webpack specific

require.contextは、モジュールのセットを動的にrequireできるwebpack固有の関数です。

コードでrequire.contextを使用でき、Rspackはビルドプロセス中に一致するモジュールを解析して参照します。

ヒント

require.contextの戻り値は、import.meta.webpackContextと同じです。より強力なimport.meta.webpackContextの使用をお勧めします。

  • Type
function requireContext(
  /**
   * A directory to search.
   */
  directory: string,
  /**
   * Whether subdirectories should be searched.
   * @default true
   */
  includeSubdirs?: boolean,
  /**
   * A regular expression to match files.
   * @default /^\.\/.*$/ (any file)
   */
  filter?: RegExp,
  /**
   * Module loading mode.
   * @default 'sync'
   */
  mode?: 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once',
): Context;
// Create a context, with files from the test directory that
// can be required with a request ending with `.test.js`.
const context = require.context('./test', false, /\.test\.js$/);
// Create a context with all files in the parent folder and
// descending folders ending with `.stories.js`.
const context = require.context('../', true, /\.stories\.js$/);
// If mode is set to 'lazy', the underlying modules will be loaded asynchronously
const context = require.context('./locales', true, /\.json$/, 'lazy');
ヒント

Rspackは静的解析を使用して、コンパイル中にrequire.contextのパラメータを解析します。そのため、パラメータはリテラルでなければなりません。

たとえば、filterの値は変数にすることはできませんし、new RegExp()によって生成された値にすることもできません。正規表現リテラルのみが可能です。

require.ensure

Rspack/Webpack specific
ヒント

require.ensure()はrspack/webpack特有のものであり、import()によって置き換えられました。

指定されたdependenciesを非同期にロードされる個別のバンドルに分割します。CommonJSモジュール構文を使用する場合、これはdependenciesを動的にロードする唯一の方法です。つまり、このコードは実行時に実行でき、特定の条件が満たされた場合にのみ依存関係をロードします。

WARNING

この機能は内部的にPromiseに依存しています。古いブラウザでrequire.ensureを使用する場合は、es6-promiseまたはpromise-polyfillなどのポリフィルを使用してPromiseをshimすることを忘れないでください。

  • Type
function requireEnsure(
  /**
   * An array of strings declaring all modules required for the code in the callback to execute.
   */
  dependencies: String[],
  /**
   * A function that webpack will execute once the dependencies are loaded.
   * An implementation of the require function is sent as a parameter to this function.
   * The function body can use this to further require() modules it needs for execution
   */
  callback: function(require),
  /**
   * A function that is executed when webpack fails to load the dependencies.
   */
  errorCallback?: function(error),
  /**
   * A name given to the chunk created by this particular require.ensure().
   * By passing the same chunkName to various require.ensure() calls,
   * we can combine their code into a single chunk, resulting in only one bundle that the browser must load.
   */
  chunkName?: String
): Context;
var a = require('normal-dep');

if (module.hot) {
  require.ensure(['b'], function (require) {
    var c = require('c');

    // Do something special...
  });
}

Data URIモジュール

Rspackは、import構文とrequire構文を使用してData URIモジュールのインポートをサポートしています。

import

import DataURI from 'data:text/javascript,export default 42';

require

require('data:text/javascript,module.exports = 42');

さらに、Base64でエンコードされたリクエストもサポートされています。

const {
  number,
  fn,
} = require('data:text/javascript;charset=utf-8;base64,ZXhwb3J0IGNvbnN0IG51bWJlciA9IDQyOwpleHBvcnQgZnVuY3Rpb24gZm4oKSB7CiAgcmV0dXJuICJIZWxsbyB3b3JsZCI7Cn0=');
ヒント

Data URIモジュールは、Loaderと組み合わせて実行時にカスタムモジュールを動的にロードするなど、仮想モジュールを実装する方法として使用できます。