# Modern.js > The Modern.js framework is a progressive web framework based on React. At ByteDance, we use Modern.js to build upper-level frameworks that have supported the development of thousands of web applications. ## Guide - [BFF](/guides/advanced-features/bff.md): BFF (Backends for Frontends) is an architectural pattern primarily used to address issues of data aggregation in front-end and back-end collaboration. Under the BFF architecture, front-end applications do not communicate directly with backend services. Instead, they interact with backend services through a dedicated BFF middleware layer, custom-made for the front end. The main problems it tries to solve include: Aggregation, mapping, clipping, and proxying of lower-level APIs according to their own business needs.Cache data for some specific scenarios to improve performance and thus improve user experience.Quickly development of new products based on existing interfaces.Interface with third-party systems, such as login authentication. Modern.js officially supported the BFF and provided the Integrated BFF to further strengthen the BFF's capabilities, mainly including the following capabilities: Quick development and debugging go live, running, building, and deploying BFF code in the same project.Minimal pure function call, directly import BFF function on the front end, and can be automatically converted into HTTP request when called.No private protocol, follow RESTful API specification, all BFF interfaces are standardized.Full TypeScript support.Meet user preferences and support multi-frame extension writing. - [Cross-Project Invocation](/guides/advanced-features/bff/cross-project.md): Based on the BFF architecture, Modern.js provides cross-project invocation capabilities, allowing BFF functions created in one project to be invoked by other projects through integrated calls, enabling function sharing and feature reuse across projects. Cross-project invocation consists of producer and consumer sides. The producer is responsible for creating and providing BFF services while generating integrated invocation SDK, and the consumer initiates requests through these SDK. - [Extend BFF Server](/guides/advanced-features/bff/extend-server.md): In some applications, developers may want to handle all BFF functions uniformly, such as authentication, logging, data processing, etc. Modern.js allows users to freely extend the BFF Server through Middleware method. - [Runtime Framework](/guides/advanced-features/bff/frameworks.md): Modern.js uses Hono.js as the BFF and Server runtime framework, so you can extend BFF Server based on the Hono.js ecosystem. Getting Request Context Sometimes in BFF functions, it's necessary to obtain the request context to handle more logic. In such cases, you can use useHonoContext to get it: :::info For more details, refer to useHonoContext. ::: Getting Cookies When getting cookies in BFF functions, you need to get the request context through useHonoContext, then use c.req.header('cookie') to get the Cookie string and parse it manually: :::caution Note The c.req.cookie() method does not exist in the current version. You need to use c.req.header('cookie') to get the Cookie string and parse it manually. ::: Defining BFF Functions When using Hono as the runtime framework, you can define interfaces through Api functions: :::info For more details about Api functions and operators, refer to Creating Extensible BFF Functions. ::: Using Middleware Hono supports a rich middleware ecosystem, and you can use middleware in BFF functions: :::info For more details about middleware, refer to Creating Extensible BFF Functions. ::: More Hono Documentation For more detailed information about Hono, please refer to the Hono official documentation. - [Basic Usage](/guides/advanced-features/bff/function.md): In a Modern.js application, developers can define API files under the api/lambda directory and export API functions from these files. In the frontend code, these API functions can be directly invoked by importing the file, which initiates the API requests. This invocation method is called unified invocation, where developers do not need to write glue code for the frontend and backend separately, thereby ensuring type safety across both. - [Creating Extensible BFF Functions](/guides/advanced-features/bff/operators.md): The previous section showed how to export a simple BFF function in a file. In more complex scenarios, each BFF function may need to do independent type validation, pre-logic, etc. Therefore, Modern.js exposes Api, which supports creating BFF functions through this API. BFF functions created in this way can be easily extended with functionality. - [Extend Request SDK](/guides/advanced-features/bff/sdk.md): The unified invocation of BFF functions is isomorphic in both CSR and SSR. The request SDK encapsulated by Modern.js relies on the Fetch API on the browser side, and on node-fetch on the server side. However, in actual business scenarios, additional processing may be required for requests or responses, such as: Writing authentication information in the request headersUniform handling of response data or errorsUsing other methods to send requests when the native fetch function is unavailable on specific platforms To address these scenarios, Modern.js provides the configure function, which offers a series of extension capabilities. You can use it to configure SSR passthrough request headers, add interceptors, or customize the request SDK. :::caution Note The configure function needs to be called before all BFF requests are sent to ensure that the default request configuration is overridden. ::: - [File Upload](/guides/advanced-features/bff/upload.md): BFF combined with runtime framework provides file upload capabilities, supporting integrated calls and pure function manual calls. BFF Function First, create the api/lambda/upload.ts file: :::tip The formData parameter in the interface processing function can access files uploaded from the client side. It is an Object where the keys correspond to the field names used during the upload. ::: Integrated Calling Next, directly import and call the function in src/routes/upload/page.tsx: :::tip Note: The input parameter type must be { formData: FormData } for the upload to succeed. ::: Manual Calling You can manually upload files using the fetch API, when calling fetch, set the body as FormData type and submit a post request. - [Improve Build Performance](/guides/advanced-features/build-performance.md): Modern.js optimizes build performance by default, but as the project becomes larger, you may encounter some build performance problems. This document provides some optional speed-up strategies, developers can choose some of them to improve the build performance. :::tip 📢 Notice The strategies in Bundle Size Optimization can also be used to improve build performance, so we won't repeat them here. ::: - [Browser Compatibility](/guides/advanced-features/compatibility.md) - [Internationalization](/guides/advanced-features/international.md): @modern-js/plugin-i18n 是 Modern.js 的国际化插件,基于 i18next 和 react-i18next 构建,为 Modern.js 应用提供完整的国际化解决方案。 - [Advanced Usage](/guides/advanced-features/international/advanced.md) - [API Reference](/guides/advanced-features/international/api.md) - [Basic Concepts](/guides/advanced-features/international/basic.md): Before integrating internationalization capabilities into your project, you need to understand internationalization-related concepts. Understanding core concepts can help you quickly establish a stable translation system and better solve various problems during use. - [Best Practices](/guides/advanced-features/international/best-practices.md) - [Configuration](/guides/advanced-features/international/configuration.md): Plugin configuration is divided into two parts: CLI configuration (modern.config.ts) and runtime configuration (modern.runtime.ts). Both need to be used together - CLI configuration is for basic plugin settings, while runtime configuration is for i18next initialization options. :::warning Function-type configurations (such as SDK loader functions) can only be set in runtime configuration (modern.runtime.ts), not in CLI configuration. This is because CLI configuration is executed at build time and cannot serialize functions. ::: - [Locale Detection](/guides/advanced-features/international/locale-detection.md): The plugin supports multiple language detection methods, which can be combined to meet different business requirements. - [Quick Start](/guides/advanced-features/international/quick-start.md): This guide will help you quickly integrate internationalization functionality into your Modern.js project. - [Resource Loading](/guides/advanced-features/international/resource-loading.md): The plugin supports three resource loading methods: HTTP backend, File System backend (FS Backend), and SDK backend. Additionally, the plugin supports chained backend, which allows combining multiple backends. - [Routing Integration](/guides/advanced-features/international/routing.md): The plugin is deeply integrated with Modern.js routing system, supporting language path prefixes and automatic path redirection. - [Low-Level Tools](/guides/advanced-features/low-level.md) - [Code Splitting](/guides/advanced-features/page-performance/code-split.md): Code splitting is a common way to optimize frontend resource loading. This article will introduce the three types of code splitting supported by Modern.js: :::info When using Modern.js Conventional routing. By default, code splitting is done according to the routing component, so you don't need to do it yourself. ::: dynamic importReact.lazyloadable - [Inline Static Assets](/guides/advanced-features/page-performance/inline-assets.md): Inline static assets refer to the practice of including the content of a static asset directly in a HTML or JS file, instead of linking to an external file. This can improve the performance of a website by reducing the number of HTTP requests that the browser has to make to load the page. However, static assets inlining also has some disadvantages, such as increasing the size of a single file, which may lead to slower loading. Therefore, in the actual scenario, it is necessary to decide whether to use static assets inlining according to the specific situation. Modern.js will automatically inline static assets that are less than 10KB, but sometimes you may need to manually control assets to force them to be inlined or not, and this document explains how to precisely control the inlining behavior of static assets. - [Bundle Size Optimization](/guides/advanced-features/page-performance/optimize-bundle.md): Bundle size optimization is an important part of optimizing your production environment because it directly affects the user experience. In this document, we will introduce some common bundle size optimization methods in Modern.js. - [React Compiler](/guides/advanced-features/page-performance/react-compiler.md): The React Compiler is an experimental compiler introduced in React 19 that can automatically optimize your React code. Before starting to use the React Compiler, it is recommended to read the React Compiler documentation to understand its features, current status, and usage. - [Logs Events](/guides/advanced-features/server-monitor/logger.md): Log events are distributed by Modern.js as events of type log. - [Metrics Events](/guides/advanced-features/server-monitor/metrics.md): Metric events are distributed by Monitors as events of type timing or counter. - [Monitors](/guides/advanced-features/server-monitor/monitors.md): Modern.js is a full-stack framework that supports both client-side and server-side development. When server-side rendering (SSR), the framework automatically injects additional logs and metrics during server runtime to help production issue diagnosis. As server code operates in Node.js environments, developers cannot directly utilize browser consoles for troubleshooting. Given that different projects may adopt varied logging libraries or data reporting platforms, the framework provides a unified approach for developers to manage built-in logging and metric collection. The Monitors module in Modern.js empowers application monitoring through two core capabilities: Monitor registration and monitoring event distribution. When developers invoke Monitors APIs, the framework propagates corresponding monitoring events to all registered Monitors. :::note Modern.js ships with a default Monitor implementation, while simultaneously allowing developers to register custom Monitors. ::: - [Source Code Build Mode](/guides/advanced-features/source-build.md): The source code build mode is used in the monorepo development scenario, allowing developers to directly reference the source code of other sub-projects within the monorepo for development. - [Custom Web Server](/guides/advanced-features/web-server.md): Modern.js encapsulates most server-side capabilities required by projects, typically eliminating the need for server-side development. However, in certain scenarios such as user authentication, request preprocessing, or adding page skeletons, custom server-side logic may still be necessary. To use the Custom Web Server in a Modern.js project, follow these steps: Install @modern-js/server-runtime dependency If the @modern-js/server-runtime dependency is not yet installed in your project, install it first: :::tip Version Consistency Make sure the version of @modern-js/server-runtime matches the version of @modern-js/app-tools in your project. All Modern.js official packages are released with a uniform version number, and version mismatches may cause compatibility issues. Check the version of @modern-js/app-tools first, then install the same version of @modern-js/server-runtime: ::: Create the server directory and configuration file Create a server/modern.server.ts file in the project root directory: After creating the file, you can write custom logic in this file. - [Path Alias](/guides/basic-features/alias.md): Path aliases allow developers to define aliases for modules, making it easier to reference them in code. This can be useful when you want to use a short, easy-to-remember name for a module instead of a long, complex path. For example, if you frequently reference the src/common/request.ts module in your project, you can define an alias for it as @request and then use `` in your code instead of writing the full relative path every time. This also allows you to move the module to a different location without needing to update all the import statements in your code. In Modern.js, there are two ways to set up path aliases: Through the paths configuration in tsconfig.json.Through the source.alias configuration. - [Using CSS-in-JS](/guides/basic-features/css/css-in-js.md): CSS-in-JS is a technique that allows you to write CSS styles within JS files. Modern.js supports the commonly used community CSS-in-JS library styled-components, which uses JavaScript's new feature Tagged template to write component CSS styles. The Modern.js plugin @modern-js/plugin-styled-components provides support for styled-components and adds server-side rendering capability for styled-components. You can use styled-components by installing the @modern-js/plugin-styled-components plugin. - [Use CSS Modules](/guides/basic-features/css/css-modules.md): CSS Modules allows us to write CSS code in a modular way, and these styles can be imported and used in JavaScript files. Using CSS Modules can automatically generate unique class names, isolate styles between different modules, and avoid class name conflicts. Modern.js supports CSS Modules by default, you don't need to add additional configuration. Our convention is to use the [name].module.css filename to enable CSS Modules. The following style files are considered CSS Modules: *.module.scss*.module.less*.module.css - [Styling](/guides/basic-features/css/css.md): Modern.js has built-in a variety of commonly used CSS solutions, including Less / Sass / Stylus preprocessors, PostCSS, CSS Modules, CSS-in-JS, and Tailwind CSS. - [Using Tailwind CSS](/guides/basic-features/css/tailwindcss.md): Tailwind CSS is a CSS framework and design system based on Utility Class, which can quickly add common styles to components, and support flexible extension of theme styles. - [Data Caching](/guides/basic-features/data/data-cache.md): The cache function allows you to cache the results of data fetching or computation, Compared to full-page rendering cache, it provides more fine-grained control over data granularity and is applicable to various scenarios such as Client-Side Rendering (CSR), Server-Side Rendering (SSR), and API services (BFF). - [Data Fetching](/guides/basic-features/data/data-fetch.md): Modern.js provides out-of-the-box data fetching capabilities. Developers can use these APIs to fetch data in their projects. It's important to note that these APIs do not help the application make requests but assist developers in managing data better and improving project performance. - [Data Writing](/guides/basic-features/data/data-write.md): In the Data Fetching section, we introduced how Modern.js fetches data. This might bring up two questions: How do I update the data returned by the Data Loader?How do I send new data to the server? In Modern.js, you can use Data Action to address these scenarios. - [Data Mocking](/guides/basic-features/debug/mock.md): Modern.js allows you to easily generate mock data so that the front-end can develop independently without depending on the back-end API. - [Local Proxy](/guides/basic-features/debug/proxy.md): Modern.js provides a way to configure the development proxy in dev.server.proxy. For example, to proxy the local interface to another address: - [Using Rsdoctor](/guides/basic-features/debug/rsdoctor.md): Rsdoctor is a Rspack build analysis tool. In Modern.js, we recommend using Rsdoctor to diagnose and analyze the build process and build outputs. - [Using Storybook](/guides/basic-features/debug/using-storybook.md): Storybook is a tool specifically designed for component debugging. It provides: A rich variety of debugging capabilitiesIntegration with some testing toolsReusable documentation contentSharing capabilitiesWorkflow automation - [Deploy Application](/guides/basic-features/deploy.md): Currently, Modern.js offers two deployment way: You can host your application in a container that includes a Node.js environment on your own, which provides flexibility for the deployment of the application.You can also deploy your application through a platform. Currently, Modern.js officially supports deployment on Netlify, Vercel, and Github pages. :::info Currently, Modern.js only supports running in a Node.js environment. Support for more runtime environments will be provided in the future. ::: - [Environment Variables](/guides/basic-features/env-vars.md): Modern.js provides support for environment variables, including built-in environment variables and custom environment variables. - [HTML Template](/guides/basic-features/html.md): Modern.js provides JSX syntax and HTML(EJS) syntax to customize the HTML template. - [Output Files](/guides/basic-features/output-files.md): This chapter will introduces the directory structure of output files and how to control the output directory of different types of files. - [Render Preprocessing](/guides/basic-features/render/before-render.md): In certain scenarios, applications need to perform preprocessing operations before rendering. Modern.js recommends using Runtime Plugins to implement this type of logic. - [Rendering Mode Overview](/guides/basic-features/render/overview.md): Modern.js supports multiple rendering modes, and different rendering modes are suitable for different scenarios. Choosing the right rendering mode can significantly improve application performance and user experience. - [React Server Components (RSC)](/guides/basic-features/render/rsc.md): React Server Components (RSC) is a new component type that allows components to be rendered in a server environment, bringing better performance and developer experience to modern web applications. - [Static Site Generation](/guides/basic-features/render/ssg.md): SSG (Static Site Generation) is a technical solution that generates complete static web pages at build time based on data and templates. This means that in a production environment, pages are pre-rendered with content and can be cached by a CDN. SSG can offer better performance and higher security for pages that do not require dynamic data. - [Rendering Cache](/guides/basic-features/render/ssr-cache.md): When developing applications, sometimes we cache computation results using hooks like React's useMemo and useCallback. By leveraging caching, we can reduce the number of computations, thus saving CPU resources and improving user experience. Modern.js supports caching server-side rendering (SSR) results, reducing the computational and rendering time during subsequent requests. This accelerates page load time and improves user experience. Additionally, caching lowers server load, conserves computational resources, and speeds up user access. - [Server-Side Rendering](/guides/basic-features/render/ssr.md): Server-Side Rendering (SSR) generates complete HTML pages on the server and sends them to the browser for direct display, without requiring additional client-side rendering. - [Streaming Server-Side Rendering](/guides/basic-features/render/streaming-ssr.md): Streaming rendering is an advanced rendering method that progressively returns content during the page rendering process, significantly improving user experience. In traditional SSR rendering, the page is rendered all at once, requiring all data to be loaded before returning the complete HTML. In streaming rendering, the page is rendered progressively, allowing content to be returned as it renders, so users can see initial content faster. :::info Default Mode Streaming SSR is the default rendering mode for Modern.js SSR. When you enable SSR, streaming rendering is available without additional configuration. If you need to switch to traditional SSR mode (waiting for all data to load before returning at once), you can configure server.ssr.mode to 'string'. For detailed information, refer to the Server-Side Rendering (SSR) documentation. ::: Compared to traditional SSR rendering: Faster Perceived Speed: Streaming rendering can progressively display content, quickly rendering the home page.Enhanced User Experience: Users can see page content faster and interact without waiting for the entire page to render.Better Performance Control: Developers can better control the loading priority and order, optimizing performance and user experience.Better Adaptability: Streaming rendering adapts better to various network speeds and device performance, ensuring good performance across different environments. - [Config Routes](/guides/basic-features/routes/config-routes.md): By default, Modern.js recommends using Convention Routes as the way to define routes. At the same time, Modern.js also provides a config-based routing capability that can be used together with convention routes or used separately. - [Routing](/guides/basic-features/routes/routes.md): Modern.js routing is based on React Router v7, offering file convention-based routing capabilities and supporting the industry-popular nested routing pattern. When an entry is recognized as conventional routing, Modern.js automatically generates the corresponding routing structure based on the file system. :::note The routing mentioned in this section all refers to conventional routing. ::: - [Import Static Assets](/guides/basic-features/static-assets.md): Modern.js supports import static assets, including images, fonts, and medias. :::tip What is Static Assets Static assets are files that are part of a web application and do not change, even when the application is being used. Examples of static assets include images, fonts, medias, stylesheets, and JavaScript files. These assets are typically stored on a web server or CDN, and delivered to the user's web browser when the Web application is accessed. Because they do not change, static assets can be cached by the browser, which helps to improve the performance of the Web application. ::: - [Import JSON Files](/guides/basic-features/static-assets/json-files.md): Modern.js supports import JSON files in code by default. You can use Rsbuild plugins to support importing YAML and Toml files and converting them to JSON format. - [Import SVG Assets](/guides/basic-features/static-assets/svg-assets.md): Modern.js supports import SVG assets and transform SVG into React components or URLs. :::tip What is SVG SVG stands for Scalable Vector Graphics. It is a type of image format that uses vector graphics to represent images. Vector graphics are different from raster graphics, which are made up of pixels. Instead, vector graphics use geometric shapes, lines, and curves to represent images. Because vector graphics are not made up of pixels, they can be scaled to any size without losing resolution or quality. ::: - [Import Wasm Assets](/guides/basic-features/static-assets/wasm-assets.md): Modern.js supports import WebAssembly assets in code. :::tip What is WebAssembly WebAssembly (Wasm) is a portable, high-performance binary format designed to execute CPU-intensive computing tasks in modern web browsers, bringing performance and reliability similar to native compiled code to the web platform. ::: - [Cypress](/guides/basic-features/testing/cypress.md): Cypress is a framework for E2E testing and component testing. To use Cypress in Modern.js, you need to install the dependencies first. You can run the following commands: Next, create a cypress.config.ts file and add the following content: - [Jest](/guides/basic-features/testing/jest.md): Jest is a JavaScript testing framework that is primarily used with React Testing Library for unit testing and Snapshot testing. To use Jest in Modern.js, you need to install the dependencies first. You can run the following commands: Next, you can run the following commands to automatically initialize Jest in your project and generate a basic jest.config.ts configuration: - [Playwright](/guides/basic-features/testing/playwright.md): Playwright is a testing framework that allows you to run tests automatically in Chromium, Firefox, and WebKit environments using a single API. You can use it to write E2E tests. To use Playwright in Modern.js, you need to install the dependencies first. You can run the following commands: The above commands will automatically install Playwright dependencies and help you install and configure it in your project through a series of prompts, including adding a playwright.config.ts file. :::info Refer to the official Playwright documentation at Install Playwright for a more detailed guide. ::: After creating with the default configuration, you can see the following files in your project: This is the default test file. Now create some new pages and test them. - [Rstest](/guides/basic-features/testing/rstest.md): Rstest is a testing framework developed by the Rspack team and built on top of Rspack for fast test execution. This guide explains how to integrate Rstest with Modern.js for web app testing. - [Vitest](/guides/basic-features/testing/vitest.md): Vitest is a testing framework driven by Vite, which can be used for unit testing in combination with React Testing Library. To use Vitest in Modern.js, you need to install the dependencies first. You can run the following commands: Next, you need to create a Vitest configuration file vitest.config.ts with the following content: For more information about Vitest configuration, you can refer to the Vitest configuration documentation. You can optionally add the vitest command to package.json: After running this command, Vitest will automatically watch your file changes and rerun the test cases. - [Build Engine](/guides/concept/builder.md): Modern.js internally encapsulates Rsbuild, using Rspack as the bundler. ::: tip What is Rsbuild? Rsbuild is a build tool based on Rspack. It is an enhanced Rspack CLI, easy-to-use, and ready-to-use out of the box. ::: - [Page Entry](/guides/concept/entries.md): Through this chapter, you can understand the entry conventions in Modern.js and how to customize entries. - [Web Server](/guides/concept/server.md): Modern.js provides an integrated Web server for applications that can run in any container environment with Node.js. Whether executing the dev command in a local development environment, running the build && serve commands in a production environment, or using the official deployment solution, it all runs through this Web server to host the application. - [Glossary](/guides/get-started/glossary.md) - [Introduction](/guides/get-started/introduction.md): Modern.js is a progressive web framework based on React. At ByteDance, we use Modern.js to build upper-level frameworks that have supported the development of thousands of web applications. Modern.js can provide developers with an ultimate Development Experience and enable applications to have better User Experience. In the process of developing React applications, developers usually need to design implementation plans for certain features or use other libraries and frameworks to solve these problems. Modern.js supports all configurations and tools needed by React applications, and has built-in additional features and optimizations. Developers can use React to build the UI of the application, and then gradually adopt the features of Modern.js to solve common application requirements, such as routing, data acquisition, and state management. It mainly includes the following features: 🚀 Rust Bundler: Modern.js uses Rsbuild/Rspack as the build tool, providing blazing fast compilation.🪜 Progressive: Create projects with the most streamlined templates, gradually enable plugin features through the generator, and customize solutions.🏠 Integration: Development and production environment web server are unique, CSR and SSR are isomorphic development, and API service calls are functions as interfaces.🕸 Convention Routing: Using file-based routing helps developers quickly set up applications. - [Quick Start](/guides/get-started/quick-start.md) - [Tech Stack](/guides/get-started/tech-stack.md): The Modern.js framework comes with built-in popular libraries and development tools from the community. In this document, you can learn about the main technology stack involved in the Modern.js framework, as well as some optional libraries and tools. - [Upgrading](/guides/get-started/upgrade.md) - [Application-Level Modules](/guides/topic-detail/module-federation/application.md): Modern.js provides runtime APIs to quickly export application-level Module Federation modules from your application. We use the application created in Using Module Federation as an example to further explain how to import application-level modules. - [Deployment](/guides/topic-detail/module-federation/deploy.md): In general, when deploying a Module Federation application, there are two key points to consider: Ensure that the remote module addresses in the consumer's configuration file are correct, and that the consumer can correctly access the producer's manifest file.Ensure that all resources in the producer's manifest file can be accessed correctly. We recommend using Modern.js's Node Server to deploy Module Federation applications for an out-of-the-box experience. - [Integrating Internationalization](/guides/topic-detail/module-federation/i18n.md): Modern.js provides the @modern-js/plugin-i18n plugin to support internationalization. When using Module Federation, you need to provide corresponding i18n integration solutions for different scenarios (components or applications). - [Introduction](/guides/topic-detail/module-federation/introduce.md): Module Federation is an architectural pattern for dividing JavaScript applications, allowing you to share code and resources among multiple JavaScript applications. In this divided model, it can help improve application performance, enhance code maintainability, and more. - [Server-Side Rendering](/guides/topic-detail/module-federation/ssr.md): @module-federation/modern-js-v3 offers powerful capabilities, enabling developers to easily combine Module Federation with server-side rendering (SSR) in Modern.js applications. - [Getting Started](/guides/topic-detail/module-federation/usage.md): To use Module Federation in Modern.js, we recommend using the official plugin @module-federation/modern-js-v3. This section will introduce how to set up both producer and consumer applications using the official plugin. First, create two applications by following the Modern.js Quick Start. - [Build FAQ](/guides/troubleshooting/builder.md): If you encounter any build-related issues, you can refer to the current document for troubleshooting. Rsbuild FAQ Modern.js is internally based on Rsbuild and encapsulates its own build tool, so you can directly refer to the FAQ document of Rsbuild: Rsbuild - Features FAQRsbuild - Exceptions FAQRsbuild - HMR FAQ How to view the final generated Rspack configuration? Modern.js provides inspect command to view the final Modern.js configuration and Rspack configuration generated by the project. Failed import other modules in Monorepo? Due to considerations of compilation performance, by default, the Modern.js does not compile files under node_modules or files outside the current project directory. Therefore, when you reference the source code of other sub-projects, you may encounter an error similar to You may need an additional loader to handle the result of these loaders. There are several solutions to this problem: You can enable the source code build mode to compile other sub-projects within the monorepo. Please refer to Source Code Build Mode for more information.You can add the source.include configuration option to specify the directories or modules that need to be additionally compiled. Please refer to Usage of source.include for more information.You can pre-build the sub-projects that need to be referenced, generate the corresponding build artifacts, and then reference the build artifacts in the current project instead of referencing the source code. Find exports is not defined runtime error? If the compilation is succeed, but the exports is not defined error appears after opening the page, it is usually because a CommonJS module is compiled by Babel. Under normal circumstances, Modern.js will not use Babel to compile CommonJS modules. If the source.include configuration option is used in the project, some CommonJS modules may be added to the Babel compilation. There are two workarounds for this problem: Avoid adding CommonJS modules to Babel compilation.Set Babel's sourceType configuration to unambiguous. Compile error "Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax"? If the following error occurs during compilation, it is usually because a CommonJS module is compiled with Babel in the project, and the solution is same as the above exports is not defined problem. For more information, please refer to issue: babel#12731. The compilation progress bar is stuck, but there is no Error log in the terminal? When the compilation progress bar is stuck, but there is no Error log on the terminal, it is usually because an exception occurred during the compilation. In some cases, when Error is caught by the build tool or other modules, the error log can not be output correctly. The most common scenario is that there is an exception in the Babel config, which is caught by the build tool, and the build tool swallows the Error in some cases. Solution: If this problem occurs after you modify the Babel config, it is recommended to check for the following incorrect usages: You have configured a plugin or preset that does not exist, maybe the name is misspelled, or it is not installed correctly.Whether multiple babel-plugin-imports are configured, but the name of each babel-plugin-import is not declared in the third item of the array. Compilation error after referencing a type from lodash If the @types/lodash package is installed in your project, you may import some types from lodash, such as the DebouncedFunc type: Modern.js will throw an error after compiling the above code: The reason is that Modern.js has enabled the babel-plugin-lodash plugin by default to optimize the bundle size of lodash, but Babel cannot distinguish between "value" and "type", which resulting in an exception in the compiled code. The solution is to use TypeScript's import type syntax to explicitly declare the DebouncedFunc type: :::tip In any case, it is recommended to use import type to import types, this will help the compiler to identify the type. ::: - [CLI FAQ](/guides/troubleshooting/cli.md): Unable to pass command line arguments correctly when using pnpm? When using pnpm to call the commands in package.json, you need to pay attention to how parameters are passed: If you need to pass parameters to pnpm, you need to put the parameters before the command. For example, using the pnpm --filter parameter to run the prepare command: If you need to pass parameters to the command, you need to put the parameters after the command. For example, in the following package.json configuration: The way to pass parameters when running the command is: :::tip Modern.js requires Node.js >= 20.19.5, and pnpm v6 does not support Node.js 20, so please use pnpm v7 or higher. ::: - [Dependencies FAQ](/guides/troubleshooting/dependencies.md): How to check the actual installed version of a dependency in the project? You can use the ls command provided by the package manager to view the version of the dependency in the project. Here are some basic examples. For detailed usage, please refer to the documentation of each package manager. npm / yarn For projects using npm or yarn, you can use the npm ls command. For example, running npm ls @modern-js/plugin will show the following result: pnpm For projects using pnpm, you can use the pnpm ls command. For example, running pnpm ls @modern-js/plugin --depth Infinity will show the following result: Getting "The engine "node" is incompatible" error during dependency installation? If you encounter the following error message during dependency installation, it means that the current environment is using a Node.js version that is too low, and you need to upgrade Node.js to a higher version. Modern.js requires Node.js version >= 20.19.5. We strongly recommend using the latest LTS version (such as Node.js 22 LTS) for the best experience. If the Node.js version of the current environment is lower than the above requirement, you can use tools such as nvm or fnm to switch versions. Here is an example of using nvm: For local development environments, it is recommended to use fnm, which has better performance than nvm and has similar usage. Getting a ReactNode type error after upgrading dependencies? After upgrading the dependencies of the project, if the following type error occurs, it means that the wrong version of @types/react is installed in the project. The reason for this problem is that the ReactNode type definition in React 18/19 is different from that in React 16/17. If there are multiple different versions of @types/react in the project, a ReactNode type conflict will occur, resulting in the above error. The solution is to lock the @types/react and @types/react-dom in the project to a unified version, such as v17. For methods of locking dependency versions, please refer to Lock nested dependency. Getting peer dependencies warnings in the console after running pnpm install? The reason for this warning is that the version range of peer dependencies declared by some third-party npm packages is inconsistent with the version range installed in Modern.js. In most cases, peer dependencies warnings will not affect the project operation and do not need to be processed separately. Please ignore the relevant warnings. What is the minimum supported version of React for the Modern.js framework? Modern.js framework requires React version >= 18.0.0. If you are using Modern.js runtime capabilities (including SSR, Streaming SSR, data loading, routing, etc.), you must use React 18 or higher. React 16 and React 17 are no longer supported.If you are only using Modern.js build capabilities (without runtime), React 16 or React 17 may theoretically work, but it is strongly recommended to upgrade to React 18 or higher for the best experience and full feature support. Type error in Modern.js configuration file? When you use the Modern.js framework, the above error occurs in the configuration file, it may be due to the inconsistent versions of Modern.js related packages. You need to manually update all @modern-js/** packages to the same version. In the monorepo, the above error may also occur due to inconsistent versions of the Modern.js framework used by different sub-projects. For information on how to unify and upgrade dependency versions, please refer to the Upgrading documentation. - [HMR FAQ](/guides/troubleshooting/hmr.md): How to troubleshooting HMR ineffective issues? There are several possible reasons why HMR may not be work. This document will cover most common causes and provide guidance for troubleshooting. Please refer to the following content for troubleshooting. Before starting the troubleshooting process, it is helpful to have a basic understanding of how HMR works: :::tip HMR Principle The browser establishes a WebSocket connection with the development server for real-time communication.Whenever the development server finishes recompiling, it sends a notification to the browser via the WebSocket. The browser then sends a hot-update.xxx request to the development server to load the newly compiled module.After receiving the new module, if it is a React project, React Refresh, an official React tool, is used to update React components. Other frameworks have similar tools. ::: After understanding the principle of HMR, you can follow these steps for basic troubleshooting: 1. Check the WebSocket Connection Open the browser console and check for the presence of the [HMR] connected. log. If it is present, the WebSocket connection is working correctly. You can continue with the following steps.If it is not present, open the Network panel in Chrome and check the status of the ws://[host]:[port]/webpack-hmr request. If the request is failed, this indicates that the HMR failed because the WebSocket connection was not successfully established. There can be various reasons why the WebSocket connection fails to establish, such as using a network proxy that prevents the WebSocket request from reaching the development server. You can check whether the WebSocket request address matches your development server address. If it does not match, you can configure the WebSocket request address using tools.devServer.client. 2. Check the hot-update Requests When you modify the code of a module and trigger a recompilation, the browser sends several hot-update.json and hot-update.js requests to the development server to fetch the updated code. You can try modifying a module and inspect the content of the hot-update.xxx requests. If the content of the request is the latest code, it indicates that the hot update request is working correctly. If the content of the request is incorrect, it is likely due to a network proxy. Check whether the address of the hot-update.xxx request matches your development server address. If it does not match, you need to adjust the proxy rules to route the hot-update.xxx request to the development server address. 3. Check for Other Causes If the above two steps do not reveal any issues, it is possible that other factors are causing the HMR to fail. For example, it could be that the code does not meet React's requirements for HMR. You can refer to the following questions for further troubleshooting. HMR not working when external React? To ensure that HMR works properly, we need to use the development builds of React and ReactDOM. If you exclude React via externals when bundling, the production build of React is usually injected through CDN, and this can cause HMR to fail. To solve this problem, you need to reference the development builds of React or not configure externals in the development environment. If you are unsure about the type of React build you are using, you can refer to the React documentation - Use the Production Build. HMR not working when setting filename hash in development mode? Usually, we only set the filename hash in the production mode (i.e., when process.env.NODE_ENV === 'production'). If you set the filename hash in the development mode, it may cause HMR to fail (especially for CSS files). This is because every time the file content changes, the hash value changes, preventing tools like mini-css-extract-plugin from reading the latest file content. Correct usage: Incorrect usage: HMR not working when updating React components? Modern.js uses React's official Fast Refresh capability to perform component hot updates. If there is a problem that the hot update of the React component cannot take effect, or the state of the React component is lost after the hot update, it is usually because your React component uses an anonymous function. In the official practice of React Fast Refresh, it is required that the component cannot be an anonymous function, otherwise the state of the React component cannot be preserved after hot update. Here are some examples of wrong usage: The correct usage is to declare a name for each component function: HMR not working when use https? If https is enabled, the HMR connection may fail due to a certificate issue, and if you open the console, you will get an HMR connect failed error. The solution to this problem is to click on "Advanced" -> "Proceed to xxx (unsafe)" on the Chrome problem page. Tips: When accessing the page through Localhost, the words "Your connection is not private" may not appear and can be handled by visiting the Network domain. - [Configuration Changes](/guides/upgrade/config.md): This document mainly introduces incompatible configuration changes and recommended migration methods when upgrading from Modern.js 2.0 to 3.0. - [Entry Changes](/guides/upgrade/entry.md): This chapter introduces changes related to page entries when upgrading from Modern.js 2.0 to 3.0. - [Other Important Changes](/guides/upgrade/other.md): This document introduces other important incompatible changes and related migration instructions when upgrading from Modern.js 2.0 to 3.0. - [Overview](/guides/upgrade/overview.md): This guide will help you upgrade from Modern.js 2.0 to Modern.js 3.0. - [Tailwind Plugin Changes](/guides/upgrade/tailwindcss.md): Modern.js 3.0 recommends integrating Tailwind CSS through Rsbuild's native approach, no longer relying on the @modern-js/plugin-tailwindcss plugin, to fully utilize Rsbuild's more flexible configuration capabilities and better build experience. - [Custom Web Server Changes](/guides/upgrade/web-server.md): This chapter covers upgrades for two types of legacy custom Server APIs: unstableMiddlewareHook These two approaches are mutually exclusive in the legacy version. When migrating, please choose the corresponding path based on the capabilities actually used in the project. ## Config - [crossProject](/configure/app/bff/cross-project.md): Type: booleanDefault: false :::tip Please refer to the Enable BFF section in Basic Usage to enable BFF functionality first. ::: This configuration is used to enable BFF cross-project invocation functionality. When enabled, the current project can be used as a BFF producer, generating an SDK that can be directly called by other projects. For detailed configuration and usage of BFF cross-project invocation, please refer to the BFF Cross-Project Invocation Guide. - [prefix](/configure/app/bff/prefix.md): Type: stringDefault: /api :::tip Please refer to the Enable BFF section in Basic Usage to enable BFF functionality first. ::: By default, the prefix for accessing routes in the BFF API directory is /api, as shown in the following directory structure: The route corresponding to api/hello.ts when accessed is localhost:8080/api/hello. This configuration option can modify the default route prefix: The corresponding route for api/hello.ts when accessed is localhost:8080/api-demo/hello. - [builderPlugins](/configure/app/builder-plugins.md): Type: RsbuildPlugin[]Default: [] Used to configure the Rsbuild plugin. Rsbuild is the build tool of Modern.js, please read Build Engine for background. If you want to know how to write Rsbuild plugins, you can refer to Rsbuild - Plugin System. - [assetPrefix](/configure/app/dev/asset-prefix.md): Type: boolean | string | 'auto'Default: '/' This configuration item is used to set the URL prefix of static resources in development mode. :::warning Please note that this configuration item is only applicable in development mode. In production mode, please use the output.assetPrefix configuration item for setting. ::: - [beforeStartUrl](/configure/app/dev/before-start-url.md): Type: () => Promise | voidDefault: undefined dev.beforeStartUrl is used to execute a callback function before opening the startUrl, this config needs to be used together with dev.startUrl. - [client](/configure/app/dev/client.md): Type: Default: Configure the client code injected by Modern.js during the development process. This can be used to set the WebSocket URL for HMR. - [hmr](/configure/app/dev/hmr.md): Type: booleanDefault: true Whether to enable Hot Module Replacement. - [host](/configure/app/dev/host.md): Type: stringDefault: 0.0.0.0 Specify the host that the dev server listens to. By default, the dev server will listen to 0.0.0.0, which means listening to all network interfaces, including localhost and public network addresses. If you want the dev server to listen only on localhost, you can set it to: - [https](/configure/app/dev/https.md): Type: boolean | { key: string; cert: string }Default: false After configuring this option, you can enable HTTPS Dev Server, and disabling the HTTP Dev Server. HTTP: HTTPS: Automatically generate certificates You can directly set https to true, Modern.js will automatically generate the HTTPS certificate based on devcert. When using this method, you need to manually install the devcert dependency in your project: Then configure dev.https to true: The devcert has some limitations, it does not currently support IP addresses yet. :::tip The https proxy automatically installs the certificate and needs root authority, please enter the password according to the prompt. The password is only used to trust the certificate, and will not be leaked or be used elsewhere. ::: Manually set the certificate You can also manually pass in the certificate and the private key required in the dev.https option. This parameter will be directly passed to the createServer method of the https module in Node.js. For details, please refer to https.createServer. Clean up cert cache The certificate created by devcert is saved in ~/Library/Application\ Support/devcert. You may do some cleanup if needed. - [lazyCompilation](/configure/app/dev/lazy-compilation.md): Type: Default: false Enable lazy compilation (compilation on demand), implemented based on Rspack's lazy compilation feature. :::info The usage of this configuration item is exactly the same as that of Rsbuild. For detailed information, please refer to 。 In Rspack build mode, ::: - [liveReload](/configure/app/dev/live-reload.md): Type: booleanDefault: true Whether to reload the page when source files are changed. - [progressBar](/configure/app/dev/progress-bar.md): Type: Default: true Whether to display progress bar during compilation. - [server](/configure/app/dev/server.md): Type: ObjectDefault: {} The config of DevServer can be modified through dev.server. compress Type: booleanDefault: true Whether to enable gzip compression for served static assets. If you want to disable the gzip compression, you can set compress to false: For more details, please refer to the Rsbuild - server.compress documentation. headers Type: RecordDefault: undefined Adds headers to all responses. For more details, please refer to the Rsbuild - server.headers documentation. historyApiFallback Type: boolean | ConnectHistoryApiFallbackOptionsDefault: false The index.html page will likely have to be served in place of any 404 responses. Enable dev.server.historyApiFallback by setting it to true: For more configuration options, please refer to the Rsbuild - server.historyApiFallback documentation. watch Type: booleanDefault: true Whether to watch files change in directories such as mock/, server/, api/. For more details, please refer to the Rsbuild - dev.watchFiles documentation. cors Type: boolean | import('cors').CorsOptions Configure CORS (Cross-Origin Resource Sharing) for the development server. The default configuration for cors in Modern.js follows Rsbuild's defaults: For more configuration options and detailed usage, please refer to the Rsbuild - server.cors documentation. proxy Type: ProxyOptions[] | RecordDefault: undefined Configure proxy rules for the dev server, and forward requests to the specified service. :::tip This option is the same as Rsbuild's server.proxy option, see Rsbuild - server.proxy for detailed usage. ::: - [setupMiddlewares](/configure/app/dev/setup-middlewares.md): Type: Default: undefined Provides the ability to execute a custom function and apply custom middlewares. - [startUrl](/configure/app/dev/start-url.md): Type: boolean | string | string[] | undefinedDefault: undefined dev.startUrl is used to set the URL of the page that automatically opens in the browser when Dev Server starts. By default, no page will be opened. You can set it to the following values: Port placeholder Since the port number may change, you can use the placeholder to refer to the current port number, and Modern.js will automatically replace the placeholder with the actual listening port number. Open the specified browser On MacOS, you can open the specified browser when Dev Server starts, by set environment variable BROWSER, support values: Google Chrome CanaryGoogle Chrome DevGoogle Chrome BetaGoogle ChromeMicrosoft EdgeBrave BrowserVivaldiChromium - [watchFiles](/configure/app/dev/watch-files.md): Type: Default: undefined Watch specified files and directories for changes. When a file change is detected, it can trigger a page reload or restart the dev server. - [writeToDisk](/configure/app/dev/write-to-disk.md): Type: boolean | ((filename: string) => boolean)Default: (file) => !file.includes('.hot-update.') Controls whether the build output from development mode is written to disk. - [sourceBuild](/configure/app/experiments/source-build.md) - [appIcon](/configure/app/html/app-icon.md): Type: Default: undefined Set the web application icons to display when added to the home screen of a mobile device: Generate the web app manifest file and its icons field.Generate the apple-touch-icon and manifest tags in the HTML file. - [crossorigin](/configure/app/html/crossorigin.md): Type: boolean | 'anonymous' | 'use-credentials'Default: false Set the crossorigin attribute of the