Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: split module methods docs #6447

Merged
merged 2 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion website/docs/en/api/_meta.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
[
"index",
"cli",
"modules",
{
"type": "dir",
"name": "modules",
"label": "Modules"
},
"node-api",
"hmr",
{
Expand Down
2 changes: 1 addition & 1 deletion website/docs/en/api/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The Command Line Interface (CLI) to configure and interact with your build. It i

When processing modules with rspack, it is important to understand the different module syntaxes – specifically the methods and variables – that are supported.

[Learn more about the modules!](/api/modules)
[Learn more about the modules!](/api/modules/module-methods)

## Node

Expand Down
142 changes: 0 additions & 142 deletions website/docs/en/api/modules.mdx

This file was deleted.

1 change: 1 addition & 0 deletions website/docs/en/api/modules/_meta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["module-methods", "module-variables"]
167 changes: 167 additions & 0 deletions website/docs/en/api/modules/module-methods.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import WebpackLicense from '@components/webpack-license';

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

# 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.

## ES6 (Recommended)

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

### import

Statically `import` the `export`s of another module.

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

You can also `import` Data URI:

```js
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.

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

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

### Dynamic import()

```ts
function(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.

```js
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](https://github.com/stefanpenner/es6-promise) or [promise-polyfill](https://github.com/taylorhakes/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.

```js
// 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

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.

```js
import(
/* webpackChunkName: "my-chunk-name" */
/* webpackPrefetch: true */
/* webpackPreload: true */
'module'
);
```

`webpackChunkName`: A name for the new chunk.

`webpackPrefetch`: Tells the browser that the resource is probably needed for some navigation in the future (Available since 0.4.5).

`webpackPreload`: Tells the browser that the resource might be needed during the current navigation (Available since 0.4.5).

## CommonJS

Rspack is also support `CommonJS` syntax natively, you can use `require` and `module.exports` methods.

## Data URI Module

Rspack supports importing Data URI modules using the `import` and `require` syntax.

**import**

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

**require**

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

In addition, Base64 encoded requests are also supported:

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

::: tip
The Data URI module can be used as a method to implement virtual modules, such as combining with a Loader to dynamically load custom modules at runtime.
:::

## Webpack

Aside from the module syntaxes described above, Rspack also support some webpack-specific methods.

#### require.context

```ts
require.context(
(directory: String),
(includeSubdirs: Boolean) /* optional, default true */,
(filter: RegExp) /* optional, default /^\.\/.*$/, any file */,
(mode: String) /* optional, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once', default 'sync' */
);
```

Specify a whole group of dependencies using a path to the `directory`, an option to `includeSubdirs`, a `filter` for more fine grained control of the modules included, and a mode to define the way how loading will work.

```js
const context = require.context('components', true, /\.html$/);
const componentA = context.resolve('componentA');
```

If mode is set to 'lazy', the underlying modules will be loaded asynchronously.

```js
const context = require.context('locales', true, /\.json$/, 'lazy');
context('localeA').then(locale => {
// do something with locale
});
```
57 changes: 57 additions & 0 deletions website/docs/en/api/modules/module-variables.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Module Variables

This section covers all **variables** available in code compiled with webpack. Modules will have access to certain data from the compilation process through `module` and other variables.

### module.hot (webpack-specific)

Indicates whether or not Hot Module Replacement is enabled and provides an interface to the process. See the [HMR API page](/api/hmr) for details.

### import.meta.webpackHot (webpack-specific)

An alias for `module.hot`, however `import.meta.webpackHot` can be used in strict ESM while `module.hot` can't.

### \_\_dirname (NodeJS)

Depending on the configuration option `node.__dirname`:

- `false`: Not defined
- `mock`: equal to `'/'`
- `true`: [node.js \_\_dirname](https://nodejs.org/api/globals.html#globals_dirname)

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

### \_\_resourceQuery (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`.

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

```ts title="file.js"
__resourceQuery === '?test';
```

### \_\_webpack_modules\_\_ (webpack-specific)

Access to the internal object of all modules.

### \_\_webpack_hash\_\_ (webpack-specific)

It provides access to the hash of the compilation.

### \_\_webpack_public_path\_\_ (webpack-specific)

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

### \_\_webpack_chunkname\_\_ (webpack-specific)

<ApiMeta addedVersion="0.4.4" />

Access to name of current chunk.

### \_\_webpack_runtime_id\_\_ (webpack-specific)

<ApiMeta addedVersion="0.4.4" />

Access the runtime id of current entry.
Loading
Loading