### Plugin Structure Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/plugin/runtime-plugins/api.mdx
A basic example demonstrating the structure of a Runtime Plugin, including its name and setup function.
```APIDOC
## Plugin Structure
A typical Runtime Plugin looks like this:
```ts
import type { RuntimePlugin } from '@modern-js/runtime';
const myRuntimePlugin = (): RuntimePlugin => ({
name: 'my-runtime-plugin',
setup: api => {
// Use the api to register hooks
api.onBeforeRender(context => {
console.log('Before rendering:', context);
});
api.wrapRoot(App => {
return props => (
);
});
},
});
export default myRuntimePlugin;
```
- `name`: A unique identifier for the plugin.
- `setup`: A function that receives an `api` object, which provides all available Runtime plugin APIs.
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/community/contributing-guide.mdx
Install all project dependencies, create package symlinks, and run the prepare script to build all packages.
```bash
pnpm install
```
--------------------------------
### Complete Render Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/runtime/core/render.mdx
This example demonstrates creating a root component with createRoot and then rendering it using the render function after an asynchronous operation.
```tsx
import { createRoot } from '@modern-js/runtime/react';
import { render } from '@modern-js/runtime/browser';
const ModernRoot = createRoot();
async function beforeRender() {
// todo
}
beforeRender().then(() => {
render();
});
```
--------------------------------
### Start Local Development Server
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/README.md
Starts a local development server. Changes are reflected live without server restarts.
```bash
$ pnpm run dev
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/README.md
Installs all necessary project dependencies using pnpm.
```bash
pnpm i
```
--------------------------------
### Start BFF and Storybook Services
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/debug/using-storybook.mdx
Run the commands to start the BFF server and Storybook, allowing Storybook components to call BFF APIs.
```bash
pnpm dev:api
pnpm storybook
```
--------------------------------
### Basic Koa Server for Frontend
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/deploy.mdx
A basic Koa server setup to serve 'Hello Modern.js'. This is a starting point before adding logic for static and HTML file serving.
```typescript
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx, next) => {
ctx.body = 'Hello Modern.js';
});
app.listen(3000);
```
--------------------------------
### Pathless Layout Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/routes/routes.mdx
Demonstrates how directory names starting with `__` are ignored in route paths, allowing for layouts without affecting the URL structure.
```bash
.\n└── routes\n ├── __auth\n │ ├── layout.tsx\n │ ├── login\n │ │ └── page.tsx\n │ └── sign\n │ └── page.tsx\n ├── layout.tsx\n └── page.tsx
```
--------------------------------
### Configure Proxy Rules
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/dev/server.mdx
Configure proxy rules for the dev server to forward requests to a specified service. This example forwards requests starting with `/api` to `https://example.com`.
```js
export default {
dev: {
server: {
proxy: {
// http://localhost:8080/api -> https://example.com/api
// http://localhost:8080/api/foo -> https://example.com/api/foo
'/api': 'https://example.com',
},
},
},
};
```
--------------------------------
### Usage Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/runtime/ssr/renderStreaming.mdx
An example demonstrating how to integrate renderStreaming within a request handler for streaming server-side rendering.
```APIDOC
## Usage Example
```tsx title="src/entry.server.tsx"
import {
renderStreaming,
createRequestHandler,
type HandleRequest,
} from '@modern-js/runtime/ssr/server';
const handleRequest: HandleRequest = async (request, ServerRoot, options) => {
// do something before render
const stream = await renderStreaming(request, , options);
// docs: https://developer.mozilla.org/en-US/docs/Web/API/TransformStream
const transformStream = new TransformStream({
transform(chunk, controller) {
// do some transform
},
});
stream.pipeThrough(transformStream);
return new Response(transformStream.readable, {
headers: {
'content-type': 'text/html; charset=utf-8',
},
});
};
export default createRequestHandler(handleRequest);
```
### Description
This example shows how to use `renderStreaming` to get a `ReadableStream` of the server-rendered HTML. It then pipes this stream through a `TransformStream` for potential modifications before returning it as a `Response` with the appropriate content type.
```
--------------------------------
### Upgrade Node.js using nvm
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/troubleshooting/dependencies.mdx
When encountering Node.js version incompatibility errors, use `nvm` to install and switch to a compatible Node.js version. This example shows how to install and set Node.js 22 LTS as the default.
```bash
# Install Node.js 22 LTS
nvm install 22 --lts
# Switch to Node.js 22
nvm use 22
# Set Node.js 22 as the default version
nvm alias default 22
```
--------------------------------
### Install Node.js 22 LTS with nvm
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/nodeVersion.mdx
These commands demonstrate how to install the Node.js 22 LTS version using nvm, set it as the default, and switch to it.
```bash
# Install the long-term support version of Node.js 22
nvm install 22 --lts
# Make the newly installed Node.js 22 as the default version
nvm alias default 22
# Switch to the newly installed Node.js 22
nvm use 22
```
--------------------------------
### Nginx Configuration for Frontend Deployment
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/deploy.mdx
Example Nginx configuration to serve a purely front-end Modern.js project. This setup directs requests for static assets and the root path to the appropriate files in the build output.
```nginx
server {
listen 80;
server_name localhost;
location / {
root .output/html/main;
index index.html;
try_files $uri $uri/ /index.html;
}
location /static {
alias .output/static;
}
}
```
--------------------------------
### Install Server Runtime Dependency
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/bff/extend-server.mdx
Before using middleware, ensure `@modern-js/server-runtime` is installed and its version matches `@modern-js/app-tools`. Use `pnpm list` to check the current version and `pnpm add` to install the matching version.
```bash
# Check the current version of @modern-js/app-tools
pnpm list @modern-js/app-tools
# Install the same version of @modern-js/server-runtime
pnpm add @modern-js/server-runtime@
```
--------------------------------
### Default BFF Prefix Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/bff/prefix.mdx
Illustrates the default directory structure and the resulting route when the prefix is '/api'.
```bash
api
└── hello.ts
```
--------------------------------
### Install styled-components Plugin and Library
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/css/css-in-js.mdx
Install the `@modern-js/plugin-styled-components` and `styled-components` dependencies using your preferred package manager.
```bash
npm install @modern-js/plugin-styled-components styled-components -D
```
```bash
yarn add @modern-js/plugin-styled-components styled-components -D
```
```bash
pnpm install @modern-js/plugin-styled-components styled-components -D
```
--------------------------------
### Example Asset Manifest JSON
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/output/enable-asset-manifest.mdx
This is an example of the `manifest.json` file generated when `enableAssetManifest` is true. It includes mappings for CSS, JavaScript, and HTML files, as well as entry points.
```json
{
"files": {
"main.css": "/static/css/main.45b01211.css",
"main.js": "/static/js/main.52fd298f.js",
"html/main/index.html": "/html/main/index.html"
},
"entrypoints": ["static/css/main.45b01211.css", "static/js/main.52fd298f.js"]
}
```
--------------------------------
### Install i18n and Module Federation Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/topic-detail/module-federation/i18n.mdx
Install the necessary i18n plugin, Module Federation plugin, and their peer dependencies. These are required for both producer and consumer applications.
```bash
pnpm add i18next react-i18next @modern-js/plugin-i18n @module-federation/modern-js-v3
```
--------------------------------
### Use npm CLI plugins
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/plugins.mdx
Install plugins from the npm registry and import them into your configuration file.
```typescript
import { myPlugin } from 'my-plugin';
export default defineConfig({
plugins: [myPlugin()],
});
```
--------------------------------
### Install @modern-js/server-runtime
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/web-server.mdx
Install the `@modern-js/server-runtime` dependency to enable custom server logic. Ensure version consistency with `@modern-js/app-tools`.
```bash
pnpm add @modern-js/server-runtime
```
--------------------------------
### Install Polyfill Plugin
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/ua-polyfill.mdx
Install the @modern-js/plugin-polyfill package using your preferred package manager.
```bash
npm install @modern-js/plugin-polyfill
```
```bash
yarn add @modern-js/plugin-polyfill
```
```bash
pnpm add @modern-js/plugin-polyfill
```
--------------------------------
### Install server-runtime Dependency
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/guides/advanced-features/bff/extend-server.mdx
Before using middleware, ensure you have the `@modern-js/server-runtime` dependency installed. Match its version with your `@modern-js/app-tools` version to avoid compatibility issues.
```bash
# Check current @modern-js/app-tools version
pnpm list @modern-js/app-tools
# Install @modern-js/server-runtime with the same version
pnpm add @modern-js/server-runtime@
```
--------------------------------
### Install Playwright Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/testing/playwright.mdx
Use these commands to install Playwright and its necessary dependencies. This process includes configuration prompts and the creation of a playwright.config.ts file.
```bash
npm init playwright
```
```bash
yarn create playwright
```
```bash
pnpm create playwright
```
--------------------------------
### Install and Use Latest Node.js LTS
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/build-performance.mdx
Use nvm to install and switch to the latest Node.js LTS version for improved build performance. This ensures compatibility and leverages performance enhancements in newer Node.js releases.
```bash
# Install the latest LTS version (e.g., Node.js 22)
nvm install --lts
# Switch to the latest LTS version
nvm use --lts
# Set the latest LTS version as the default
nvm alias default lts/*
# View Node version
node -v
```
```bash
# Install Node.js 22 LTS
nvm install 22 --lts
# Switch to Node.js 22
nvm use 22
# Set Node.js 22 as the default version
nvm alias default 22
# View Node version
node -v
```
--------------------------------
### Producer Manifest Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/topic-detail/module-federation/deploy.mdx
An example of a producer's `mf-manifest.json` file, showing the `publicPath` which is determined by the `assetPrefix` configuration.
```json
{
"id": "remote",
"name": "remote",
"metaData": {
"name": "remote",
"publicPath": "https://my-remote-module/"
},
"shared": [ /* xxx */ ],
"remotes": [],
"exposes": [ /* xxx */ ]
}
```
--------------------------------
### Default Playwright Test Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/testing/playwright.mdx
This is the default test file generated by Playwright. It includes basic tests for checking the page title and navigating to a 'Get started' link.
```typescript
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();
// Expects page to have a heading with the name of Installation.
await expect(
page.getByRole('heading', { name: 'Installation' }),
).toBeVisible();
});
```
--------------------------------
### Build All Packages
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/community/contributing-guide.mdx
Execute the prepare command to build all packages within the repository.
```shell
pnpm run prepare
```
--------------------------------
### 2.0 Version Layout Configuration
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/guides/upgrade/entry.mdx
Example of how layout configuration and initialization were defined in version 2.0, exported from `routes/layout.tsx`.
```tsx
export const config = () => ({
router: { supportHtml5History: false },
});
export const init = context => {
context.adminData = 'admin';
};
```
--------------------------------
### Serve Project Locally
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/get-started/quick-start.mdx
Run this command in your project directory to start the production server locally. Verify that the build artifacts function correctly by accessing the provided URLs.
```bash
pnpm run serve
Modern.js Framework
info Starting production server...
> Local: http://localhost:8080/
> Network: http://192.168.0.1:8080/
```
--------------------------------
### Define a Runtime Plugin
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/render/before-render.mdx
Implement a runtime plugin by defining its name and setup function. The setup function receives an API object that allows hooking into lifecycle events like `onBeforeRender`.
```typescript
import type { RuntimePlugin } from '@modern-js/runtime';
const myRuntimePlugin = (): RuntimePlugin => ({
name: 'my-runtime-plugin',
setup: api => {
api.onBeforeRender(context => {
// Logic to execute before rendering
console.log('Before rendering:', context);
});
},
});
export default myRuntimePlugin;
```
--------------------------------
### api.onBeforeDev
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/plugin/cli-plugins/api.mdx
Allows custom logic to run before the development server starts. This hook is suitable for pre-development checks or setup operations.
```APIDOC
## api.onBeforeDev
### Description
Add additional logic before starting the development server.
### Parameters
- `devFn` (function) - Required - A function to be executed before starting the development server, without parameters, can be asynchronous.
### Execution Phase
Before executing the `dev` command to start the development server.
### Example
```typescript
api.onBeforeDev(async () => {
// Check if the port is occupied
await checkPortAvailability(3000);
});
```
```
--------------------------------
### api.onBeforeBuild
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/plugin/cli-plugins/api.mdx
Allows executing custom logic immediately before the build process starts. This hook is useful for pre-build checks or setup.
```APIDOC
## api.onBeforeBuild
### Description
Add additional logic before the build starts.
### Method
`api.onBeforeBuild(buildFn: () => void | Promise)`
### Parameters
- `buildFn` (function): A function to be executed before the build, without parameters, can be asynchronous.
### Execution Phase
Before executing the build process.
### Corresponding Rsbuild Hook
[onBeforeBuild](https://v2.rsbuild.rs/plugins/dev/hooks#onbeforebuild)
### Example
```typescript
api.onBeforeBuild(() => {
// Perform some environment checks before building
});
```
```
--------------------------------
### Configure Dev Server Start URL Options
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/dev/start-url.mdx
Set `dev.startUrl` to `true` to open the default preview page, a specific URL string, or an array of URLs to open multiple pages.
```javascript
export default {
dev: {
// Open the project's default preview page, equivalent to `http://localhost:`
startUrl: true,
// Open the specified page
startUrl: 'http://localhost:8080',
// Open multiple pages
startUrl: ['http://localhost:8080', 'http://localhost:8080/about'],
},
};
```
--------------------------------
### Define BFF API with Query Parameters
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/hono.mdx
Define API interfaces using Hono's `Api` function and operators like `Get` and `Query`. This example demonstrates defining a GET endpoint that accepts a 'id' query parameter validated by Zod.
```typescript
import { Api, Get, Query } from '@modern-js/plugin-bff/server';
import { z } from 'zod';
const QuerySchema = z.object({
id: z.string(),
});
export const getUser = Api(
Get('/user'),
Query(QuerySchema),
async ({ query }) => {
return {
id: query.id,
name: 'Modern.js',
email: 'modernjs@bytedance.com',
};
},
);
```
--------------------------------
### Project Initialization Output
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/init-app.mdx
The output indicates successful project creation and suggests next steps for development.
```bash
🚀 Welcome to Modern.js
📦 Creating project "myapp"...
✨ Project created successfully! 🎉
📋 Next, you can run the following commands:
📁 Enter the project directory:
cd myapp
🔧 Initialize Git repository:
git init
📥 Install project dependencies:
pnpm install
⚡ Start the development server:
pnpm start
```
--------------------------------
### Plugin Structure Example
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/plugin/plugin-system.mdx
Defines the basic structure of a Modern.js plugin, including its name, dependencies, and setup function. Use this as a template for creating your own plugins.
```typescript
import type { Plugin } from '@modern-js/plugin';
const myPlugin: Plugin = {
name: 'my-awesome-plugin', // The unique identifier of the plugin (required)
// Plugin dependencies and execution order (optional)
pre: [], // List of plugin names to execute before this plugin, defaults to an empty array
post: [], // List of plugin names to execute after this plugin, defaults to an empty array
required: [], // List of required plugins; if a dependent plugin is not registered, an error will be thrown, defaults to an empty array
usePlugins: [], // List of plugin instances used internally, defaults to an empty array
// Register new Hooks (optional)
registryHooks: {},
// The entry function of the plugin (required)
setup(api) {
// The core logic of the plugin, calling plugin APIs through the api object
api.modifyRspackConfig(config => {
/* ... */
});
api.onPrepare(() => {
/* ... */
});
// ... Other API calls
},
};
export default myPlugin;
```
--------------------------------
### Preview Production Build Locally
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/toolkit/create/template/README.md
Run this command to serve the production build locally and preview your application before deployment.
```bash
pnpm serve
```
--------------------------------
### Get Request Context with useHonoContext
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/hono.mdx
Access the Hono request context within BFF functions to retrieve request details like the URL. Ensure '@modern-js/server-runtime' is installed.
```typescript
import { useHonoContext } from '@modern-js/server-runtime';
export const get = async () => {
const c = useHonoContext();
console.info(`access url: ${c.req.url}`);
return 'Hello Modern.js';
};
```
--------------------------------
### Access BFF API from Frontend
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/bff/extend-server.mdx
In the frontend `src/routes/page.tsx`, use the integrated `get` method from `@api/hello` to fetch data from the BFF endpoint. This example displays the fetched message.
```typescript
import { useState, useEffect } from 'react';
import { get as hello } from '@api/hello';
export default () => {
const [text, setText] = useState('');
useEffect(() => {
async function fetchMyApi() {
const { message } = await hello();
setText(message);
}
fetchMyApi();
}, []);
return {text}
;
};
```
--------------------------------
### Example Server Route Access with Base URL
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/server/base-url.mdx
After running `dev`, observe how the base URL prefix is automatically added to local and network access points.
```bash
> Local: http://localhost:8080/base/
> Network: http://192.168.0.1:8080/base/
```
--------------------------------
### Starting Modern Dev Server
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/commands.mdx
Run `modern dev` to initiate the development server. It provides local and network URLs for accessing the application.
```bash
$ modern dev
info Starting dev server...
> Local: http://localhost:8080/
> Network: http://192.168.0.1:8080/
```
--------------------------------
### Migrate to Rstest Prompt
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/testing/rstest.mdx
This prompt guides a coding agent to migrate a Modern.js project from Jest or Vitest to Rstest. It emphasizes installing the 'migrate-to-rstest' skill and using the `@modern-js/adapter-rstest` for integration.
```prompt
Migrate this Modern.js project from Jest or Vitest to Rstest.
First install and use the migrate-to-rstest skill. If it is not installed, install it with:
npx skills add rstackjs/agent-skills --skill migrate-to-rstest
Follow the migrate-to-rstest skill instructions and the official Rstest migration guides:
- Jest: https://rstest.rs/guide/migration/jest
- Vitest: https://rstest.rs/guide/migration/vitest
Modern.js-specific requirement:
- Install and use @modern-js/adapter-rstest together with @rstest/core.
- Create or update rstest.config.ts to import withModernConfig from @modern-js/adapter-rstest.
- Reuse the Modern.js app configuration with extends: withModernConfig().
- Do not replace this with a plain Rstest config unless the project explicitly does not need Modern.js config integration.
```
--------------------------------
### Adding a New Entry with Modern New
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/commands.mdx
Execute `npx modern new` and follow the prompts to create a new application entry point.
```text
$ npx modern new
? Please select the operation you want: Create Element
? Please select the type of element to create: New "entry"
? Please fill in the entry name: entry
```
--------------------------------
### Example File Size Output
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/performance/print-file-size.mdx
Illustrates the typical output format when file sizes are printed after a production build, showing file names, sizes, and gzipped sizes.
```bash
info Production file sizes:
File Size Gzipped
dist/static/js/lib-react.09721b5c.js 152.6 kB 49.0 kB
dist/html/main/index.html 5.8 kB 2.5 kB
dist/static/js/main.3568a38e.js 3.5 kB 1.4 kB
dist/static/css/main.03221f72.css 1.4 kB 741 B
```
--------------------------------
### Self-Controlled Routing with React Router
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/concept/entries.mdx
When using self-controlled routing, you define your routes manually using React Router within `src/App.tsx`. This example shows basic route setup for the index and about pages.
```tsx
import { BrowserRouter, Route, Routes } from '@modern-js/runtime/router';
export default () => {
return (
index} />
about} />
);
};
```
--------------------------------
### Create Basic Entry Files
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/concept/entries.mdx
After creating a new entry directory, create the essential files for routing and styling within its `routes/` subdirectory.
```bash
touch src/new-entry/routes/index.css
touch src/new-entry/routes/layout.tsx
touch src/new-entry/routes/page.tsx
```
--------------------------------
### Configure Self-Routing in App.tsx
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/components/self-route-example.mdx
This example shows how to set up conditional routing based on the environment (client or server). It uses `BrowserRouter` for client-side navigation and `StaticRouter` for server-side rendering. Ensure you have the necessary routing dependencies installed.
```tsx
import { BrowserRouter, Route, Routes } from '@modern-js/runtime/router';
import { StaticRouter } from '@modern-js/runtime/router/server';
import { use } from 'react';
import { RuntimeContext } from '@modern-js/runtime';
const Router = typeof window === 'undefined' ? StaticRouter : BrowserRouter;
export default () => {
const context = use(RuntimeContext);
const pathname = context?.request?.pathname;
return (
index} />
about} />
);
};
```
--------------------------------
### Get Application Context in Plugin
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/plugin/cli-plugins/api.mdx
Retrieves and logs application context information within a plugin's hook. This example shows how to access the current mode (production/development) and the bundler type after the `onPrepare` hook is executed.
```typescript
api.onPrepare(() => {
const appContext = api.getAppContext();
console.log(
`The current project is running in ${
appContext.isProd ? 'production' : 'development'
} mode`,
);
console.log(`Bundler: ${appContext.bundlerType}`);
});
```
--------------------------------
### Initialize New App with Rspack
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/init-rspack-app.mdx
Use the Modern.js CLI to create a new application. Select your preferred language and package manager during the interactive setup.
```bash
$ npx @modern-js/create@latest myapp
? Please select the programming language: TS
? Please select the package manager: pnpm
```
--------------------------------
### Define BFF Function with Api and Query Operator
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/components/hono.mdx
When using Hono as the runtime, define API endpoints using the `Api` function. This example demonstrates defining a GET endpoint with a query parameter schema validation using Zod.
```typescript
import { Api, Get, Query } from '@modern-js/plugin-bff/server';
import { z } from 'zod';
const QuerySchema = z.object({
id: z.string(),
});
export const getUser = Api(
Get('/user'),
Query(QuerySchema),
async ({ query }) => {
return {
id: query.id,
name: 'Modern.js',
email: 'modernjs@bytedance.com',
};
},
);
```
--------------------------------
### Define a GET API Function
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/bff/function.mdx
Export a function named `get` to handle GET requests. The return value will be serialized and sent as the response.
```typescript
export const get = async () => {
return {
name: 'Modern.js',
desc: 'A modern web engineering solution',
};
};
```
--------------------------------
### Define a GET BFF Function
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/guides/advanced-features/bff/function.mdx
Export a `get` async function to handle GET requests. The return value will be the response body of the API endpoint.
```typescript
export const get = async () => {
return {
name: 'Modern.js',
desc: '现代 web 工程方案',
};
};
```
--------------------------------
### 迁移 tools.devServer 配置 (middlewares)
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/guides/upgrade/config.mdx
将 V2 的 `tools.devServer.after`、`before`、`devMiddleware` 配置迁移到 V3 的 `dev.setupMiddlewares`。`writeToDisk` 配置也已移至 `dev`。
```typescript
// v2
export default {
tools: {
devServer: {
before: [...],
after: [...],
devMiddleware: {
writeToDisk: true
}
}
}
};
// v3
export default {
dev: {
setupMiddlewares: [...],
writeToDisk: true
}
};
```
--------------------------------
### Install i18n Plugin and Peer Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/international/install-command.mdx
Install the i18n plugin, ensuring it matches the version of `@modern-js/app-tools` in your project. `i18next` and `react-i18next` are peer dependencies and must be installed separately.
```bash
pnpm list @modern-js/app-tools
```
```bash
pnpm add @modern-js/plugin-i18n@ i18next react-i18next
```
--------------------------------
### Inspect Configuration Environment
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/commands.mdx
Demonstrates how to use the `--env` option with the `modern inspect` command to view configurations for a specific environment, such as production.
```bash
modern inspect --env production
```
--------------------------------
### Custom Server Entry Point
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/hooks/src/entry.server.mdx
Customize the server-side rendering entry point by creating `src/entry.server.ts`. This example shows how to add custom logic, such as appending HTML content or setting custom headers, before returning the response.
```tsx
import {
renderString,
createRequestHandler,
type HandleRequest,
} from '@modern-js/runtime/ssr/server';
const handleRequest: HandleRequest = async (request, ServerRoot, options) => {
// do something before rendering
const body = await renderString(request, , options);
const newBody = body + 'Byte-Dance
';
return new Response(newBody, {
headers: {
'content-type': 'text/html; charset=UTF-8',
'x-custom-header': 'abc',
},
});
};
export default createRequestHandler(handleRequest);
```
--------------------------------
### Build a Specific Package
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/community/contributing-guide.mdx
Navigate to the package directory and run the build command to compile a specific package.
```shell
# Replace some-path with the path of the package you want to work on
cd ./packages/some-path
pnpm run build
```
--------------------------------
### Route Configuration with Plain Objects
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/runtime/router/router.mdx
Demonstrates how to configure routes using plain JavaScript objects passed to `createBrowserRouter`.
```APIDOC
## Route Configuration with Plain Objects
### Description
Routes can be configured using plain JavaScript objects passed to the `createBrowserRouter` function. Each object represents a route with properties like `element`, `path`, `loader`, `action`, and `errorElement`.
### Example
```javascript
const router = createBrowserRouter([
{
// it renders this element
element: ,
// when the URL matches this segment
path: 'teams/:teamId',
// with this data loaded before rendering
loader: async ({ request, params }) => {
return fetch(`/fake/api/teams/${params.teamId}.json`, {
signal: request.signal,
});
},
// performing this mutation when data is submitted to it
action: async ({ request }) => {
return updateFakeTeam(await request.formData());
},
// and renders this element in case something went wrong
errorElement: ,
},
]);
```
```
--------------------------------
### Build Module for Production
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/server/prod-server/README.md
Compile and bundle the module for production deployment with this command.
```bash
pnpm run build
```
--------------------------------
### Install SSG Plugin with Specific Version
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/enable-ssg.mdx
Install the `@modern-js/plugin-ssg` package, specifying the same version as your `@modern-js/app-tools` to maintain consistency.
```bash
# Install the same version of @modern-js/plugin-ssg
pnpm add @modern-js/plugin-ssg@
```
--------------------------------
### dev.setupMiddlewares Configuration
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/dev/setup-middlewares.mdx
Provides the ability to execute a custom function and apply custom middlewares.
```APIDOC
## dev.setupMiddlewares
### Description
Allows you to execute a custom function and apply custom middlewares to the development server.
### Type
```ts
type RequestHandler = (req: any, res: any, next: () => void) => void;
type ExposeServerApis = {
sockWrite: (
type: string,
data?: string | boolean | Record,
) => void;
};
type SetupMiddlewares = Array<
(
middlewares: {
unshift: (...handlers: RequestHandler[]) => void;
push: (...handlers: RequestHandler[]) => void;
},
server: ExposeServerApis,
) => void
>;
```
### Default
`undefined`
```
--------------------------------
### Install BFF Plugin Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/enable-bff.mdx
Install the BFF plugin using pnpm. Ensure version consistency with `@modern-js/app-tools`.
```bash
pnpm add @modern-js/plugin-bff
```
--------------------------------
### Basic Routing Structure
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/apis/app/hooks/src/routes.mdx
Demonstrates how directory names under routes/ map to URL paths for basic routing.
```bash
.\ routes\n ├── page.tsx\n └── user\n └── page.tsx
```
--------------------------------
### Configure Storybook Main File
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/debug/using-storybook.mdx
Set up the main Storybook configuration file (`.storybook/main.ts`) to specify stories, addons, and the framework.
```typescript
import type { StorybookConfig } from 'storybook-react-rsbuild'
const config: StorybookConfig = {
stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: ['storybook-addon-modernjs'],
framework: 'storybook-react-rsbuild',
}
export default config
```
--------------------------------
### Install @modern-js/server-runtime with Specific Version
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/web-server.mdx
Install `@modern-js/server-runtime` with a specific version that matches your `@modern-js/app-tools` version to avoid compatibility issues.
```bash
# Install the same version of @modern-js/server-runtime
pnpm add @modern-js/server-runtime@
```
--------------------------------
### Use Port Placeholder in Start URL
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/dev/start-url.mdx
Use the `` placeholder in `dev.startUrl` to automatically insert the current listening port number.
```javascript
export default {
dev: {
startUrl: 'http://localhost:/home',
},
};
```
--------------------------------
### Check and Install BFF Plugin Version
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/enable-bff.mdx
Verify the version of `@modern-js/app-tools` and install `@modern-js/plugin-bff` with the matching version to avoid compatibility issues.
```bash
# Check the current version of @modern-js/app-tools
pnpm list @modern-js/app-tools
# Install the same version of @modern-js/plugin-bff
pnpm add @modern-js/plugin-bff@
```
--------------------------------
### Basic Config Routes Setup
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/routes/config-routes.mdx
Define basic routes using the `defineRoutes` function. The `route` function is used here to map a component file to a URL path.
```typescript
import { defineRoutes } from '@modern-js/runtime/config-routes'
export default defineRoutes(({ route, layout, page, $ }, fileRoutes) => {
return [
route("home.tsx", "/"),
]
})
```
--------------------------------
### Install SSG Plugin
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/enable-ssg.mdx
Install the `@modern-js/plugin-ssg` package using pnpm. Ensure version consistency with `@modern-js/app-tools` to avoid compatibility issues.
```bash
pnpm add @modern-js/plugin-ssg
```
--------------------------------
### Install Rstest and Modern.js Adapter
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/testing/rstest.mdx
Install the base dependencies for Rstest and the Modern.js adapter. This command adds the necessary packages as development dependencies.
```bash
npm install @rstest/core @modern-js/adapter-rstest -D
```
--------------------------------
### Run Production Build
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/build-output.mdx
Execute this command to generate production artifacts for your project. It initiates the build process and displays file sizes upon completion.
```bash
$ pnpm run build
> modern build
Modern.js Framework
info Starting production build...
info Type checker is enabled. It may take some time.
ready Client compiled in 6.19 s
info Production file sizes:
File Size Gzipped
dist/routes-manifest.json 0.74 kB 0.28 kB
dist/static/css/async/page.d7915515.css 1.4 kB 0.69 kB
dist/static/js/main.5ae469e7.js 3.0 kB 1.3 kB
dist/html/index/index.html 6.0 kB 2.6 kB
dist/static/js/async/page.ddc8a4c1.js 19.2 kB 6.7 kB
dist/static/js/34.171fffdb.js 21.3 kB 7.1 kB
dist/static/js/lib-router.8995a55e.js 55.3 kB 18.1 kB
dist/static/js/lib-lodash.53ec3384.js 71.4 kB 24.8 kB
dist/static/js/lib-react.b5856db9.js 140.0 kB 45.2 kB
dist/static/js/lib-polyfill.86c452b3.js 213.3 kB 69.9 kB
Total size: 531.8 kB
Gzipped size: 176.7 kB
```
--------------------------------
### Create src/modern.runtime.ts
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/configure/app/runtime/0-intro.mdx
If the `src/modern.runtime.ts` file does not exist, create it using the touch command.
```bash
touch src/modern.runtime.ts
```
--------------------------------
### Run Development Server
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/debug-app.mdx
Execute this command in your project's root directory to start the Modern.js development server. Access the application via the provided local or network URLs.
```bash
pnpm run dev
```
```bash
$ pnpm run dev
> modern dev
Modern.js Framework
ready Client compiled in 0.86 s
> Local: http://localhost:8080/
> Network: http://192.168.0.1:8080/
```
--------------------------------
### 迁移 tools.devServer 配置 (compress, headers, historyApiFallback, watch)
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/zh/guides/upgrade/config.mdx
将 V2 的 `tools.devServer` 下的 `compress`、`headers`、`historyApiFallback`、`watch` 配置迁移到 V3 的 `dev.server` 下对应配置。
```typescript
// v2
export default {
tools: {
devServer: {
compress: true,
headers: {
'X-Custom-Header': 'custom-value',
},
historyApiFallback: true,
watch: true,
},
},
};
// v3
export default {
dev: {
server: {
compress: true,
headers: {
'X-Custom-Header': 'custom-value',
},
historyApiFallback: true,
watch: true,
},
},
};
```
--------------------------------
### Install react-server-dom-rspack
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/render/rsc.mdx
Install the necessary dependency for React Server Components with Rspack. Ensure React and React DOM are upgraded to version 19.2.4 or above.
```bash
npm install react-server-dom-rspack@0.0.1-beta.1
```
--------------------------------
### Preview Local Deployment
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/topic-detail/module-federation/deploy.mdx
After running `modern deploy`, use the `node .output/index` command to preview the deployed application locally and verify Module Federation functionality.
```bash
node .output/index
```
--------------------------------
### Basic Route Configuration
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/routes/config-routes.mdx
A basic example demonstrating how to use the `page` function to explicitly specify page routes for the home, about, and contact pages.
```typescript
export default defineRoutes(({ page }, fileRoutes) => {
return [
// Use page function to explicitly specify page route
page("home.tsx", "/"),
page("about.tsx", "about"),
page("contact.tsx", "contact"),
]
})
```
--------------------------------
### Install Browser Mode Dependencies
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/testing/rstest.mdx
Install additional dependencies for Rstest browser mode, including the browser adapter, React support, and Playwright. These are development dependencies.
```bash
npm install @rstest/browser @rstest/browser-react playwright -D
```
--------------------------------
### Configure Browserslist for Development and Production
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/advanced-features/build-performance.mdx
Define separate `browserslist` configurations for development and production environments in `package.json`. This allows for broader compatibility in production while optimizing build times in development by targeting only the latest browser versions.
```json
{
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
```
--------------------------------
### Install pnpm
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/prerequisites.mdx
Install the pnpm package manager globally. Modern.js recommends using pnpm for dependency management, though yarn and npm are also supported.
```bash
npm install -g pnpm@10
```
--------------------------------
### Add Scripts for BFF and Storybook
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/guides/basic-features/debug/using-storybook.mdx
Add scripts to `package.json` to start the BFF server and Storybook, enabling proxy for API calls during Storybook development.
```json
{
"scripts": {
"dev:api": "modern dev --api-only",
"storybook": "BFF_PROXY=1 storybook dev -p 6006 --no-open",
}
}
```
--------------------------------
### Check App Tools Version
Source: https://github.com/web-infra-dev/modern.js/blob/main/packages/document/docs/en/components/enable-ssg.mdx
Before installing the SSG plugin, check the current version of `@modern-js/app-tools` to ensure compatibility. Use this version when installing the SSG plugin.
```bash
# Check the current version of @modern-js/app-tools
pnpm list @modern-js/app-tools
```