--- url: /guide/more/faq.md --- # FAQ ## How to use only a specific feature of Rsdoctor? When we **only need** the [Bundle Size](/guide/usage/bundle-size.md) bundle size analysis feature **within** Rsdoctor, we can add the corresponding [features](/config/options/features.md) option when configuring the Rsdoctor plugin. Refer to the code snippet below: ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; new RsdoctorRspackPlugin({ features: ['bundle'], // Represents enabling only the bundle size analysis feature }); ``` ## Loader timing data is inaccurate? The timing data provided by Rsdoctor for loaders is an **estimated time**. The reason accurate timing cannot be measured is that loader execution can be both **asynchronous** and **synchronous** functions, the bundler will **parallelize the execution** of multiple non-conflicting loader functions, and since **JavaScript is single-threaded**, multiple loader functions can **compete for the current task queue**. Furthermore, the **asynchronous logic within loader functions cannot be recognized**, causing a single loader function to potentially **span across** the execution of multiple other loaders. As a result, there are three possible cases, as shown in the following diagram: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-cases.jpeg) Therefore, the loader timing provided by Rsdoctor is an **estimated** value. The timing data we provide accurately reflects scenario 1 and scenario 2 from the diagram. As for scenario 3, we are still exploring solutions. ## `out of memory` error when using `Rsdoctor` for building If you encounter an `out of memory` error, you can try the following two methods, with the first one being recommended: ### Method 1 Increase the Node.js memory limit, for example: `NODE_OPTIONS=--max-old-space-size=8096`. ### Method 2 This issue is often caused by storing source code information during the build process, which exceeds the memory limit. You can configure the `noCode` or `noAssetsAndModuleSource` field in `output.reportCodeType` to alleviate this issue. [output.reportCodeType](/config/options/output.md#reportcodetype) ## No Bundled/Parsed Size for Modules in bundle analysis? ### Issue Description The difference between `Source Size` and `Bundled Size`: - **Source Size**: The original size of the Module source code file (marked in cyan in the image below). - **Bundled Size**: The final code size of the Module after bundling and minification (marked in blue in the image below).\\ - **Gzip Size**: The final code size of the Module after gzip compression (marked in yellow in the image below). ![](https://assets.rspack.rs/others/assets/rsdoctor/all-in-one-after.png) ### Solution If you only have Source Size but no Bundled Size, or **there is no Module drill-down in Tree Map** (i.e., no Module chunks), you need to **manually enable SourceMap**. **Note: Only enable SourceMap when Rsdoctor is enabled, do not affect production builds.** - The following scenario requires manually enabling SourceMap: ![](https://assets.rspack.rs/others/assets/rsdoctor/all-in-one-before.png) Configuration example: ```js rspack.config.mjs export default { devtool: 'cheap-source-map', // or other devtool configuration }; ``` Rsdoctor supports the following SourceMap configurations: - source-map - hidden-source-map - inline-source-map - cheap-source-map - cheap-module-source-map - nosources-source-map ## Bundle analysis page no `Bundled Size`? ### Issue Description The difference between `Source Size` and `Bundled Size`: - **Source Size**: The original size of the Module source code file (marked in purple in the image below). - **Bundled Size**: The final code size of the Module after bundling and minification (marked in cyan in the image below). ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-overall.png) ### Root Cause When [optimization.concatenateModules](https://rspack.rs/config/optimization#optimizationconcatenatemodules) is set to `true`, Rsdoctor cannot use `acorn` to parse the build artifacts and break down the actual code size of each **Module**, therefore it cannot display the `Bundled Size`. ### Solution :::danger **Important Note:** You must check the `RSDOCTOR` environment variable and not modify ConcatenateModules directly! ConcatenateModules is enabled by default in production environments. Disabling it in production builds will increase the bundle size. ::: When enabling Rsdoctor analysis, set **concatenateModules to false** as shown below. **Note: Disabling `concatenateModules` will slightly increase bundle size, creating differences from production builds.** ```js rspack.config.mjs export default { optimization: { concatenateModules: process.env.NODE_ENV === 'production' && !process.env.RSDOCTOR, // Must check RSDOCTOR environment variable, do not modify concatenateModules directly! }, }; ``` - In the rspeedy project, configure it in `rspeedy.config.ts`: ```js rspeedy.config.ts export default { tools: { rspack(config, { env }) { if (process.env.RSDOCTOR === 'true') { config.optimization = { ...config.optimization, concatenateModules: false, }; return config; } }, }, }; ``` ## The loader of CssExtractRspackPlugin takes too long When using Rsdoctor to analyze the compilation time of Rspack projects, you may find that the loader of [CssExtractRspackPlugin](https://rspack.rs/plugins/rspack/css-extract-rspack-plugin) takes a long time. However, this figure does not represent the actual time taken by the CssExtractRspackPlugin's loader; it also includes the time taken by other loaders involved in compiling this module. - Reason: The loader in [CssExtractRspackPlugin](https://rspack.rs/plugins/rspack/css-extract-rspack-plugin) asynchronously calls other loaders during the pitch phase and waits for the callback results after these loaders execute. Therefore, the time taken by CssExtractRspackPlugin actually includes the execution time of other loaders and idle time. ![](https://assets.rspack.rs/rsdoctor/css-extract-loader.png) ## Using Rsdoctor with Re.Pack or Custom Bundle Extensions Rsdoctor now supports custom JavaScript bundle file extensions beyond the standard `.js` extension. This is particularly useful for projects like Re.Pack that use `.bundle` extensions. ### Supported Extensions By default, Rsdoctor recognizes the following JavaScript bundle extensions: - `.js` - Standard JavaScript files - `.bundle` - Re.Pack and other custom bundlers ### No Configuration Required If your project generates bundle files with a `.bundle` extension (e.g., `main.bundle`, `vendor.bundle`), Rsdoctor will automatically: - Parse and analyze `.bundle` files alongside `.js` files - Display `.bundle` files in the Bundle Analyzer Graph - Include `.bundle` assets in JavaScript asset statistics - Support source map analysis for `.bundle` files ### How It Works The detection logic has been updated in the following areas: 1. **Bundle Parsing**: The `parseBundle` function now accepts both `.js` and `.bundle` extensions when analyzing bundle contents. 2. **Asset Filtering**: Asset summary and filtering functions treat `.bundle` files as JavaScript assets. 3. **File Type Detection**: All file extension matching utilities include `.bundle` as a recognized JavaScript extension. ### Example Use Case Re.Pack projects typically generate bundles with the `.bundle` extension: ``` dist/ ├── index.bundle ← Now supported! ├── vendor.bundle ← Now supported! ├── styles.css └── assets/ ``` Rsdoctor will automatically detect and analyze these `.bundle` files without any additional configuration. --- url: /guide/more/rules.md --- # Rule index List of the error codes[E1001](#)Duplicate Packages[E1002](#)Cross Chunks Packages[E1003](#)Loader Performance Optimization[E1004](#)ECMA Version Check[E1005](#)Default Import Check[E1006](#)Module Mixed Chunks[E1007](#)Tree Shaking Side Effects Only[E1008](#)CJS Require Cannot Tree-ShakeE1001Duplicate Packagesbundle#### Description There is a same name package which is bundled in multiple versions in your application. This negatively impacts the bundle size of your application. #### General Solution Add an entry in `resolve.alias` to configure Webpack to route any package references to a single specified path. For example, if `lodash` is duplicated in your bundle, the following configuration would make all Lodash imports refer to the `lodash` instance found at `./node_modules/lodash`: ```` { alias: { lodash: path.resolve(__dirname, 'node_modules/lodash') } } ```` --- url: /guide/rules/rule-custom.md --- # Custom extension rules ## Introduction Considering that users may have their own specific rule definition requirements, Rsdoctor provides an external interface for users to customize their own rule checks in addition to the built-in rules. The external extension interface needs to be configured on the Rsdoctor plugin through the `extends` field, and its configuration is also placed in the `rules` field. See the example below: ```ts // src/rules/assets-count-limit.ts import { defineRule } from '@rsdoctor/core/rules'; export const AssetsCountLimit = defineRule(() => ({ meta: { category: 'bundle', severity: 'Warn', title: 'assets-count-limit', defaultConfig: { limit: 10, }, }, check({ chunkGraph, report, ruleConfig }) { const assets = chunkGraph.getAssets(); if (assets.length > ruleConfig.limit) { report({ message: 'The count of assets is bigger than limit', detail: { type: 'link', link: 'https://rsdoctor.rs/zh/guide/start/quick-start', // This link just for show case. }, }); } }, })); ``` ```ts // rsbuild.config.ts import { AssetsCountLimit } from './rules/assets-count-limit'; export default { tools: { bundlerChain: (chain) => { chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { linter: { level: 'Error', extends: [AssetsCountLimit], rules: { 'assets-count-limit': [ 'on', { limit: 1, // rule custom configs }, ], }, }, }, ]); }, }, }; ``` You can follow the detailed steps below to define and write custom rules. ## Steps for custom rules ### 1. Installation When writing custom rules, in addition to installing the basic `@rsdoctor/rspack-plugin (@rsdoctor/webpack-plugin)` dependencies, you also need to install `@rsdoctor/core` and use the defineRule function from `@rsdoctor/core/rules` to define unified Rsdoctor rules. ```sh [npm] npm add @rsdoctor/core -D ``` ```sh [yarn] yarn add @rsdoctor/core -D ``` ```sh [pnpm] pnpm add @rsdoctor/core -D ``` ```sh [bun] bun add @rsdoctor/core -D ``` ```sh [deno] deno add npm:@rsdoctor/core -D ``` ### 2. Writing rules To write rules, you need to use the `defineRule` function, which takes a function as input and returns an object in a fixed format. Refer to the following example: ```ts // src/rules/some-rule.ts import { defineRule } from '@rsdoctor/core/rules'; const ruleTitle = 'check-rule'; const ruleConfig = { // some rule configs }; export const CheckRule = defineRule(() => ({ meta: { category: 'bundle', // rule category severity: 'Warn', // rule severity title: ruleTitle, // rule title defaultConfig: { // rule default config }, }, check(ruleContext) { // rule check... }, })); ``` The `meta` field contains the fixed configuration and content of this rule, and the `check` field contains the callback that includes the specific logic for rule checking. Their types are as follows. #### meta object For the definition of the meta type, please refer to [RuleMeta](#rulemeta). ##### Property meanings - meta - category - info: Defines the category of the rule: compilation rule or build packaging rule. - type: 'compile' | 'bundle'. - title - info: The title of the rule, used to display in the Rsdoctor report page. - type: string | generics, can be passed down through generics. - severity - info: The severity level of the rule. - type: Refer to the ErrorLevel type below. - default: 'Warn' - defaultConfig - info: The default configuration of the rule. Custom rules may require specific configurations, and defaultConfig can be used to configure the default rule configuration. - type: Generics, can be defined through generics. As shown in the example above. - referenceUrl - info: The documentation link for the rule. - type: string. #### check function The check function is mainly used for rule judgment. The parameter `ruleContext` is all the build information that Rsdoctor integrates during the build analysis process, and its type is defined as follows. You can use the build information in the body of the check function to make custom rule judgments. After the judgment, if the rule check fails, you can report it using the `report` method in the parameter. See the next step for details. ##### CheckCallback type ```ts type CheckCallback = ( context: RuleCheckerContext, ) => void | Promise; ``` [`RuleCheckerContext` type definition, please refer to the details](#rulecheckercontext) ##### Example The following example is a custom rule that limits the number of assets: ```ts // src/rules/some-rule.ts const CheckRule = defineRule(() => ({ // ..... check({ chunkGraph, report, ruleConfig }) { const assets = chunkGraph.getAssets(); if (assets.length > ruleConfig.limit) { report({ message: 'The count of assets is bigger than limit', detail: { type: 'link', link: 'https://rsdoctor.rs/zh/guide/start/quick-start', // This link just for show case. }, }); } }, })); ``` ### 3. Reporting rule results To report errors, you need to use the `report` method in the `check` callback function's parameter. The `report` method's parameters mainly include the following parts: - message: The error message. - document: File data used to describe the location of the error code and code position. - suggestions: Rule suggestions. - detail: Detailed information, mainly providing additional data to the frontend. For detailed type definitions, refer to: [ReportData](#reportdata) ### 4. Displaying rule results The `report` function will pass the error information of custom rules to the compilation's errors or warnings. It will display the rule results in the terminal during the build process, and even interrupt the build. At the same time, Rsdoctor also has two components that can be used to display rules. For more details, see [Display Components](#display-components). - Basic Rule Warning Component ![](https://assets.rspack.rs/others/assets/rsdoctor/rule-1.jpeg) ## Display components ### Basic rule warning component - Component Type [LinkRule Type](#linkrulestoredata) - Component Input - type - The type of the component. - value: 'link'. - title - The title of the rule. - type: string. - description - The description of the rule. The data comes from the `message` or `detail.description` in the `report` function: ```js report({ message: 'The count of assets is bigger than limit', detail: { // ...... description: 'The count of assets is bigger than limit', }, }); ``` - type: string. - level - The level of the rule. - type: warn | error. - link: - The details of the rule. The data comes from `detail.link`: ```js report({ detail: { // ...... link: 'http://....', }, }); ``` - type:string。 - Example ```ts report({ message: 'The count of assets is bigger than limit', detail: { type: 'link', link: 'https://rsdoctor.rs/zh/guide/start/quick-start', // This link just for show case. }, }); ``` - Display Components ![](https://assets.rspack.rs/others/assets/rsdoctor/rule-1.jpeg) - Component Code [Code](https://github.com/web-infra-dev/rsdoctor/blob/main/packages/components/src/components/Alert/link.tsx) ### Code display component - Component Type [CodeViewRule Type](#codeviewrule) - Component Input - type - The type of the component. - value: 'code-view'. - title - The title of the rule. - type: string. - description - The description of the rule. The data comes from the `message` or `detail.description` in the `report` function: ```js report({ message: 'The count of assets is bigger than limit', detail: { // ...... description: 'The count of assets is bigger than limit', }, }); ``` - type: string. - level - The level of the rule. - type: warn | error. - file - Code details for display. - [type](#codeviewrule): - file: string, code file path. - content: string, code content. - ranges: SourceRange, code line and column ranges. - Example ```js const detail { type: 'code-view', file: { path: document.path, content: document.content, ranges: [node.loc!], }, }; report({ message, document, detail, }); ``` - [More Examples](https://github.com/web-infra-dev/rsdoctor/blob/main/packages/core/src/rules/rules/default-import-check/index.ts#L103) - Component Display ![](https://assets.rspack.rs/others/assets/rsdoctor/rule-3.jpeg) - Component Code: [Code](https://github.com/web-infra-dev/rsdoctor/blob/main/packages/components/src/components/Alert/view.tsx) ## Type definitions ### RuleMeta ```ts interface RuleMeta< Config = DefaultRuleConfig, Title extends DefaultRuleTitle = DefaultRuleTitle, > { title: Title; category: severity: ErrorLevel; referenceUrl?: string; defaultConfig?: Config; } /** Error Level */ export enum ErrorLevel { Ignore = 0, Warn = 1, Error = 2, } ``` ### RuleCheckerContext ```ts interface RuleCheckerContext { /** Project root directory */ root: string; /** Current rule configuration */ ruleConfig: Config; /** Project configuration */ configs: ConfigData; /** Build errors */ errors: Error[]; /** Chunk graph */ chunkGraph: ChunkGraph; /** Module graph */ moduleGraph: ModuleGraph; /** Package graph */ packageGraph: PackageGraph; /** Loader data */ loader: LoaderData; /** * Report Error * @param {any} error - error info * @param {any} replacer - Replace the original error */ report(error: ReportData, replacer?: any): void; } ``` ### ReportData ```ts interface ReportData { /** Error message */ message: string; /** File data */ document?: ReportDocument; /** Diagnostic suggestions */ suggestions?: Suggestion; /** * Detailed information * - Mainly provides additional data for the frontend */ detail?: any; } /** Error file information */ interface ReportDocument { /** file path */ path: string; /** Is it a transformed code */ isTransformed?: boolean; /** code content */ content: string; range: Range; } ``` ### LinkRuleStoreData ```ts interface BaseRuleStoreData extends Pick { /** * unique of error */ id: number | string; /** * title of alerts */ title: string; /** * description of alerts */ description?: string; /** * level of error */ level: 'warn' | 'error'; /** * rule doc link */ link?: string; } interface LinkRuleStoreData extends BaseRuleStoreData { type: 'link'; } ``` ### CodeViewRule ```ts interface CodeViewRuleStoreData extends BaseRuleStoreData { type: 'code-view'; file: { /** * file path */ path: string; /** * the code content */ content: string; /** * fix highlight range in source */ ranges?: SourceRange[]; }; } /** Source code location */ interface SourcePosition { line?: number; column?: number; index?: number; } /** Source code range */ interface SourceRange { start: SourcePosition; end?: SourcePosition; } ``` ## Tools ### AST processing When performing rule detection and analysis, it is common to perform AST analysis on modules and other operations. To provide more auxiliary functions, we also provide `@rsdoctor/utils/rule-utils` in the `@rsdoctor/utils` package, which contains many useful utility functions and methods. ```ts /** This includes the type definitions for all AST nodes */ type Node = /* SyntaxNode */; interface parser { /** AST iterator */ walk, /** * Compile code * - The root node is `Node.Program` */ parse, /** * Compile the next expression * - The root node is `Node.ExpressionStatement` */ parseExpressionAt, /** Assertion methods */ asserts, /** Utility methods */ utils, } /** Document class */ interface Document { /** Get the position in the text at the given offset */ positionAt!: (offset: number) => Position | undefined; /** Get the position in the file at the given point */ offsetAt!: (position: Position) => number | undefined; } ``` The `asserts` assertion method set provides type assertion methods for all AST nodes, while the `utils` utility method set provides commonly used methods such as determining whether certain statements have the same semantics and retrieving Import nodes. ### Reporting code position Some errors require providing the position of the code, so the content of the `document` field needs to be provided. However, there is an important distinction here: each module actually has two sets of code, transformed and source, which means the code after being processed by the loader and the user's original code. The AST is actually the transformed code format. To facilitate display for users, we need to use the original code as much as possible. Therefore, after selecting the corresponding AST node, users need to use the SourceMap module provided by the module to convert the position information to the original code. If the module does not have the original code or SourceMap for some special reasons, then using the transformed code/position is more appropriate. A typical workflow is as follows: ```ts const module: SDK.ModuleInstance; const node: Node.ImportDeclaration; /** The default type is optional, but in reality, they all have values */ const transformedRange = node.loc!; /** If the module's SourceMap is not available, this value is null */ const sourceRange = module.getSourceRange(transformedRange); /** Get the code */ const source = mod.getSource(); // Determine which value to use based on whether the original position is generated const range = (sourceRange ?? transformed) as Linter.Range; const content = sourceRange ? source.source : source.transformed; report({ document: { path: module.path, content, range, }, }); ``` ## Data reporting Please go to [Data Reporting](/guide/rules/upload-data.md) for viewing. --- url: /guide/rules/rules.md --- # Built-in rules ## Introduction :::tip Please refer to the [Linter Type](#linter-type) in this document for the type definition of `linter`. ::: ### \[E1001] Duplicate packages #### Rule details - The `Duplicate Packages` card displays the number of duplicate third-party packages in the project. Clicking the image allows you to view the specific details of the duplicate third-party packages. Note: The third-party packages referred to here are all bundled third-party packages.
- Duplicate Package Warning Card ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-alerts.png) - Clicking the icon to expand the duplicate package details allows you to see: the name, version, size, and reference files of the duplicate package. - Clicking the **「Show Relations」** on the far right can view the specific reference chain and the corresponding reference file code position of this third-party package. - Clicking the **「!(exclamation mark)」** icon on the far right can view the specific explanation of the rule for the duplicate third-party package. #### Configuration - Configuration Example: ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { plugin: [ new RsdoctorRspackPlugin({ linter: { level: 'Error', extends: [], rules: { 'duplicate-package': [ 'Error', { checkVersion: 'minor', ignore: ['chalk', '@babel/runtime'], }, ], }, }, }), ], }; ``` ##### Type - **ignore**: Configures the packages to be ignored. - **checkVersion**: Refers to the maximum version level to be checked, for example: if set to `minor`, then the duplicate package will no longer check the `major` level differences. **Default is `major`**. ```ts interface Config { checkVersion: keyof typeof CheckVersion; ignore: string[]; } enum CheckVersion { null = 0, prerelease = 0x1, prepatch = 0x10, patch = 0x100, preminor = 0x1000, minor = 0x10000, premajor = 0x100000, major = 0x1000000, } ``` #### Duplicate package optimization problem Please refer to the [Duplicate Package Optimization Solution](/blog/topic/duplicate-pkg-problem.md). Clicking 「**More**」 can view the corresponding rule explanation. ### \[E1002] Cross chunks package The cross chunks duplicate package rule can scan **duplicate packages in different `chunks`**. These duplicate packages may also lead to redundant code in the build artifacts, depending on the business logic and the size of the redundant code. - Display - Module refers to the module that is repeatedly packaged in multiple chunks. - Chunks are the build artifacts that are repeatedly packaged. ![](https://assets.rspack.rs/others/assets/rsdoctor/cross-chunks-package.png) #### Solution Please refer to [\[E1002\] Cross Chunks Packages](/guide/more/rules.md) ### \[E1003] Loader performance optimization This module allows you to visually see some warning information about our project's compilation, which can help us further optimize the project's compilation performance. #### Solution Please refer to [\[E1003\] Loader Performance Optimization](/guide/more/rules.md) #### Configuration type - **ignore**: Can include strings or regular expressions, used to specify the loaders to be ignored. - **threshold**: Represents the total time threshold for the loader, in milliseconds. If the loader's execution time exceeds this threshold, it may trigger warnings or errors. The default value is 5000 milliseconds. - **extensions**: Strings or regular expressions, used to specify the file extensions that need to be matched in rule checks. By default, it includes common file types such as js, css, jpg, jpeg, png, gif, webp, and svg. ```ts interface Config { /** * loaders which should be ignore. */ ignore: (string | RegExp)[]; /** * threshold which the loader total costs. * @unit millisecond * @default 5000 */ threshold: number; /** * the file extensions which will be match in rule check. * @default ["js", "css", "jpg", "jpeg", "png", "gif", "webp", "svg"] */ extensions: (string | RegExp)[]; } ``` ### \[E1004] ECMA version check This rule is used to detect incompatible advanced syntax. When scanning the rule, the configuration of `browserslist` is prioritized; if `browserslist` is not configured, manual detection is required, as shown below: ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { plugin: [ new RsdoctorRspackPlugin({ linter: { rules: { 'ecma-version-check': [ 'Warn', { ecmaVersion: 2015, // targets: ["chrome >= 53"], }, ], }, }, }), ], }; ``` #### Type definitions ```ts type CheckSyntaxOptions = { /** * The target browser range of the project. * Its value is a standard browserslist array. */ targets?: string[]; /** * Used to exclude a portion of source files during detection. * You can pass in one or more regular expressions to match the paths of source files. */ exclude?: CheckSyntaxExclude; /** * Used to exclude files by output path before detection. * You can pass in one or more regular expressions to match the paths of source files. */ excludeOutput?: CheckSyntaxExclude; /** * The minimum ECMAScript syntax version that can be used in the build artifact. * The priority of `ecmaVersion` is higher than `targets`. */ ecmaVersion?: EcmaVersion; /** * Used to ignore specified syntax error messages after detection. * You can pass in one or more error message types to ignore. */ excludeErrorLogs?: SyntaxErrorKey[]; }; ``` For more `ECMA Version Check` configuration options, please refer to [ECMA Version Check Options](https://github.com/rstackjs/rsbuild-plugin-check-syntax?tab=readme-ov-file#options) ### \[E1005] Default import check Typically, Rspack automatically supports different types of modules, but in some cases, compatibility operations may fail. For example, when using `Default Import` to import a `cjs` module, if the module does not have a compatible statement (such as `exports.default`), issues may arise. #### Solution Please refer to [\[E1005\] Default Import Check](/guide/more/rules.md) #### Configuration - **ignore**:Configure to ignore some imported files. ```ts interface Config { /** Packages that need to be ignored */ ignore: string[]; } ``` ### \[E1006] Module Mixed Chunks When a module is included in both **initial chunks** and **async chunks**, the same module code is bundled into multiple chunks, increasing output size and potentially affecting first-screen load and cache efficiency. - **Initial chunks**: Chunks loaded with the main entry (e.g. entry points, synchronous `import` in the main bundle). - **Async chunks**: Chunks loaded on demand via dynamic `import()` or similar. #### Rule details - In the **「Module Mixed Chunks」** tab of Bundle Alerts, all modules that appear in both initial and async chunks are listed. - Each entry shows: module path, **Initial Chunks** list, and **Async Chunks** list, so you can locate duplicated modules. #### Common causes - **Same module referenced in two ways**: The module is both synchronously `import`ed in the main bundle or entry, and dynamically `import()`ed somewhere else, so the bundler emits it in both initial and async chunks. - **A file is both an entry and an async chunk**: For example, a utility module is configured as an entry and also `import()`ed in app code, so it appears in the entry’s initial chunk and in a dynamically loaded async chunk. - **splitChunks overlapping with entry**: A path is split into an async chunk via `splitChunks` / `chunkSplit`, but that path is also an entry or a main-bundle dependency, leading to mixed chunk types. #### Solutions and recommendations 1. **Use a single import style**\ Prefer one way to reference a module: either all synchronous imports (in initial) or all dynamic `import()` (in async). Avoid having the same file both synchronously imported in the main bundle and dynamically imported elsewhere. 2. **Review entry vs dynamic loading**\ If a file is both an entry and part of an async chunk, either remove one of those usages or treat the file as a shared dependency and extract it into a single shared chunk via build config, so both initial and async chunks reference it instead of duplicating it. 3. **Adjust splitChunks / chunkSplit**\ Check rules for that module path in `optimization.splitChunks` (Rspack/Webpack) or `performance.chunkSplit` (Rsbuild), and avoid the same module being split into both initial and async chunks. Use `chunks: 'async'` or `chunks: 'initial'` where appropriate, or control which chunk type it goes into via `cacheGroups` and `test` / `chunks`. 4. **Trace dependencies**\ From the reported module path and chunk list, search the codebase for references to that module, distinguish sync vs dynamic imports, then converge to a single chunk type or extract a common chunk as above. #### Configuration - **ignore**: Module path patterns to ignore (string match: if the module path contains any of these strings, it is ignored). ```ts interface Config { /** Module path fragments to ignore */ ignore: string[]; } ``` Configuration example: ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { plugin: [ new RsdoctorRspackPlugin({ linter: { rules: { 'module-mixed-chunks': ['Warn', { ignore: ['node_modules/'] }], }, }, }), ], }; ``` ### \[E1007] Tree Shaking Side Effects Only Rule key: `tree-shaking-side-effects-only` This rule detects modules that are pulled in and bundled solely due to side effects. This is often caused by unintended tree-shaking failures (e.g. missing or incorrect `"sideEffects"` field in `package.json`, or non-tree-shakeable import patterns), resulting in the entire module being bundled even though none of its exports are used. #### Common causes - The package's `package.json` is missing `"sideEffects": false` (or incorrectly set to `true`), preventing the bundler from pruning unused exports. - An import statement like `import 'some-module'` or `import './styles.css'` is being treated as a side-effect-only import, but the intended use was to consume exports. - Barrel files (index files that re-export many things) cause the whole module to be kept alive when only a side-effect import is present. #### Solutions 1. **Audit import statements**: Make sure you are actually importing and using named exports from this module. Replace bare side-effect imports with explicit named imports when you intend to use the module's exports. 2. **Set `"sideEffects"` correctly**: In the module's `package.json`, set `"sideEffects": false` if the module has no global side effects, so the bundler can safely tree-shake unused exports. 3. **Avoid unintended side-effect imports**: Remove or convert `import 'module'` patterns to explicit `import { foo } from 'module'` patterns where the exports are needed. #### Configuration - **ignore**: Module path patterns to ignore (string match: if the module path contains any of these strings, it is ignored). - **include**: Module path patterns to include when the module is under `node_modules` (by default, modules in `node_modules` are skipped). ```ts interface Config { /** Module path fragments to ignore */ ignore: string[]; /** * Module path patterns to include when the module is under node_modules. * Example: ['react', '@babel/runtime'] */ include: string[]; } ``` Configuration example: ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { plugins: [ new RsdoctorRspackPlugin({ linter: { rules: { 'tree-shaking-side-effects-only': [ 'Warn', { ignore: ['src/polyfills'], include: ['some-lib'], }, ], }, }, }), ], }; ``` ## Linter type - The type definition for the `linter` field is as follows: ```ts /** Linter options */ interface Options { rules?: RulesMap; level?: SeverityString; extends?: ExtendRuleData[]; } /** * Linting level * - `'Warn'` runs only rules categorized as `'Warn'` * - `'Error'` runs all rules */ type SeverityString = 'Warn' | 'Error'; /** Rule level */ type SeverityInput = SeverityString | 'off' | 'on'; /** Rule configuration */ type RulesMap = Record; /** Single rule configuration */ type RuleConfigItem = // Only error level, this level has higher priority than the rule's own configuration | SeverityInput // In the case of an array, the first item is the error level, and the second item is the rule configuration | [SeverityInput, unknown]; ``` If you want to **disable a rule**, you can set `SeverityInput` to `off`, as shown in the following example: ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { plugin: [ new RsdoctorRspackPlugin({ linter: { level: 'Error', extends: [], rules: { 'duplicate-package': 'off', }, }, }), ], }; ``` --- url: /guide/rules/upload-data.md --- # Data upload To perform data upload, you need to use the interface of custom extension rules. Please refer to [Custom Extension Rules](/guide/rules/rule-custom.md) for more information. The same approach used for custom extension rules can also be used for collecting and uploading user data. The only difference is that you don't need to report any errors in the check function. For example: ```ts // src/rules/upload-data.ts import { defineRule } from '@rsdoctor/core/rules'; export const UploadData = defineRule(() => ({ meta: { category: 'bundle', severity: 'Warn', title: 'upload-data', defaultConfig: { limit: 10, }, }, check({ chunkGraph, moduleGraph, ruleConfig }) { // upload some data Upload({ chunkGraph, moduleGraph }); }, })); ``` ```ts // rsbuild.config.ts import { UploadData } from './rules/upload-data'; export default { tools: { bundlerChain: (chain) => { chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { linter: { level: 'Warn', extends: [UploadData], }, }, ]); }, }, }; ``` --- url: /guide/start/action.md --- # GitHub Action Integration Rsdoctor provides an official GitHub [rsdoctor-action](https://github.com/web-infra-dev/rsdoctor-action) for easy integration of Rsdoctor analysis functionality in CI/CD workflows. Through GitHub Action, you can automatically perform bundle diff analysis on the build output and monitor and prevent bundle degradation, continuously optimizing project performance. ![](https://assets.rspack.rs/others/assets/rsdoctor/github-actions-opt.png) ## Quick Start ### Step 1: Install Rsdoctor Plugin in Your Project **1. Follow the [Quick Start](/guide/start/quick-start.md) guide to install the Rsdoctor plugin in your project and configure it according to your project type.** **2. You need to use Brief mode and add `'json'` to the `type` array so that the analysis data can be uploaded in the subsequent GitHub Action.** For detailed configuration, see [output options](/config/options/output.md). - Example below, Rsbuild integration example: ```typescript // rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default defineConfig({ plugins: [pluginReact()], tools: { rspack: { plugins: [ new RsdoctorRspackPlugin({ output: { mode: 'brief', options: { type: ['json'], }, }, }), ], }, }, }); ``` ### Step 2: Configure GitHub Workflow Create a `.github/workflows/ci.yml` file in your GitHub repository as shown in the example below. Please note the following points: - `file_path`: Required, path to the Rsdoctor JSON data file. - `target_branch`: Optional, target branch name, defaults to 'main'. If you want to use a dynamic target branch, i.e., automatically get the target branch of the current pull request instead of a fixed main branch, you can use the following configuration: ```yaml target_branch: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || github.event.repository.default_branch }} ``` - `dispatch_target_branch`: Optional, used to specify the target branch when manually triggered (workflow\_dispatch). - `on` indicates when the workflow runs, commonly set to `pull_request` and `push`, and also supports `workflow_dispatch` for manual triggering. - On `pull_request`, Rsdoctor Action fetches baseline and current and performs bundle diff analysis. - On `push` (i.e., after PR merge), it updates and uploads the baseline. - `workflow_dispatch` allows you to manually trigger the workflow from the GitHub Actions page. This mode combines the behavior of `push` and `pull_request`: it uploads baseline data, and if `dispatch_target_branch` is specified, it also performs baseline comparison analysis. - Before executing rsdoctor-action, build your project with the Rsdoctor plugin enabled to generate the Rsdoctor JSON data file. ```yaml name: Bundle Analysis on: pull_request: types: [opened, synchronize, reopened] push: branches: - main # or your target branch name workflow_dispatch: # Optional, allows manual triggering inputs: target_branch: description: 'Target branch to compare against' required: false default: 'main' type: string jobs: bundle-analysis: runs-on: ubuntu-latest permissions: # Allow commenting on commits contents: write # Allow commenting on issues issues: write # Allow commenting on pull requests pull-requests: write # Allow reading workflow runs and downloading artifacts for baseline comparison actions: read steps: - name: Checkout uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4 with: fetch-depth: 0 token: ${{ secrets.GITHUB_TOKEN }} - name: Setup Pnpm run: | npm install -g corepack@latest --force corepack enable - name: Setup Node.js uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: 'pnpm' - name: Install Dependencies and Build run: | pnpm install pnpm run build - name: Bundle Analysis uses: web-infra-dev/rsdoctor-action@main with: file_path: 'dist/.rsdoctor/rsdoctor-data.json' # Default 'main'. If you want to use a dynamic target branch, i.e., automatically get the target branch of the current pull request instead of a fixed main branch, you can use the following configuration: # ${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || github.event.repository.default_branch }} target_branch: 'main' # Target branch for manual trigger dispatch_target_branch: ${{ github.event.inputs.target_branch }} ``` ## View Reports After submitting the above configuration file to your repository, GitHub Actions will automatically run under the specified trigger conditions and generate Rsdoctor analysis reports. You will see bundle size change comparison prompts in GitHub CI, as shown below: ![](https://assets.rspack.rs/others/assets/rsdoctor/github-actions-opt.png) Additionally, clicking "Download Bundle Diff Report" allows you to download Rsdoctor's diff report for detailed diff data viewing. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-all.png) > For detailed Bundle Diff report content, see [Bundle Diff Usage Guide](/guide/usage/bundle-diff.md). ## Troubleshooting ### Common Issues **Q: Action fails with "❌ Rsdoctor data file not found"** - Ensure your build process generates Rsdoctor JSON data, the default path is `/rsdoctor-data.json`. - Check if file\_path points to the correct location - Verify that the Rsdoctor plugin is properly configured in your build tool **Q: If you see the message "No baseline data found", what does it mean?** - This is normal for the first run or for new repositories, because no baseline has been uploaded yet. The baseline data will be created after the first merge into the main branch. ## More Resources - [rsdoctor-action GitHub Repository](https://github.com/web-infra-dev/rsdoctor-action) --- url: /guide/start/ai.md --- # AI To help AI better understand Rsdoctor's features, configuration, and best practices so it can provide more accurate assistance during day-to-day development and troubleshooting, Rsdoctor provides the following capabilities: - [Agent Skills](#agent-skills) - [MCP Server](#mcp-server) - [llms.txt](#llmstxt) - [Markdown docs](#markdown-docs) - [AGENTS.md](#agentsmd) ## Agent Skills Agent Skills are domain-specific knowledge packs that can be installed into Agents, enabling them to give more accurate and professional suggestions or perform actions in specific scenarios. In the [rstackjs/agent-skills](https://github.com/rstackjs/agent-skills) repository, there are many skills for the Rstack ecosystem. The skills related to Rsdoctor include: - [rsdoctor-analysis](https://github.com/rstackjs/agent-skills#rsdoctor-skills): Use Rsdoctor for build analysis and provide optimization recommendations. In Coding Agents that support skills, you can use the [skills](https://www.npmjs.com/package/skills) package to install a specific skill with the following command: ```sh [npx] npx skills add rstackjs/agent-skills --skill rsdoctor-analysis ``` ```sh [yarn] yarn dlx skills add rstackjs/agent-skills --skill rsdoctor-analysis ``` ```sh [pnpm] pnpm dlx skills add rstackjs/agent-skills --skill rsdoctor-analysis ``` ```sh [bunx] bunx skills add rstackjs/agent-skills --skill rsdoctor-analysis ``` ```sh [deno] deno run -A npm:skills add rstackjs/agent-skills --skill rsdoctor-analysis ``` After installation, simply use natural language prompts to trigger the skill, for example: ``` Use Rsdoctor to analyze this project and provide optimization suggestions ``` ## MCP Server Rsdoctor provides MCP Server so AI tools can query your local build analysis data. See the [MCP Server](/guide/usage/mcp.md) documentation. ## llms.txt [llms.txt](https://llmstxt.org/) is a standard that helps LLMs discover and use project documentation. Rsdoctor follows this standard and publishes the following two files: - [llms.txt](https://rsdoctor.rs/llms.txt): A structured index file containing the titles, links, and brief descriptions of all documentation pages. ``` https://rsdoctor.rs/llms.txt ``` - [llms-full.txt](https://rsdoctor.rs/llms-full.txt): A full-content file that concatenates the complete content of every documentation page into a single file. ``` https://rsdoctor.rs/llms-full.txt ``` You can choose the file that best fits your use case: - `llms.txt` is smaller and consumes fewer tokens, making it suitable for AI to fetch specific pages on demand. - `llms-full.txt` contains the complete documentation content, so AI doesn't need to follow individual links - ideal when you need AI to have a comprehensive understanding of Rsdoctor, though it consumes more tokens and is best used with AI tools that support large context windows. ## Markdown docs Every Rsdoctor documentation page has a corresponding `.md` plain-text version that can be provided directly to AI. On any doc page, you can click "Copy Markdown" or "Copy Markdown Link" under the title to get the Markdown content or link. ``` https://rsdoctor.rs/guide/start/intro.md ``` Providing the Markdown link or content allows AI to focus on a specific chapter, which is useful for targeted troubleshooting or looking up a particular topic. ## AGENTS.md You can create an `AGENTS.md` file in the root of a project that uses Rsdoctor. This file follows the [AGENTS.md](https://agents.md/) specification and provides key project information to Agents. Here is an example of Rsdoctor-related content you can add to `AGENTS.md`: ```markdown wrapCode # AGENTS.md You are an expert in JavaScript, Rsdoctor, and build analysis. ## Tools ### Rsdoctor - Run `RSDOCTOR=true npm run build` to build the app with Rsdoctor ## Docs - Rsdoctor: https://rsdoctor.rs/llms.txt ``` You can also customize it for your project, adding more details about the project structure, overall architecture, and other relevant information so Agents can better understand your project. ::: tip If you are using Claude Code, you can create a `CLAUDE.md` file and reference the `AGENTS.md` file in it. ```markdown title="CLAUDE.md" @AGENTS.md ``` ::: --- url: /guide/start/cicd.md --- # CI/CD tutorial In CI/CD, there is often a desire to upload historical reports to the CDN as historical records. Because it's not convenient to achieve instant use in the standard mode, the **Brief** mode is supported. ## Brief mode In Brief mode, data reports are integrated into a single HTML page, making it easy for users to view historical build data in a summary form within CI/CD and other scenarios. ### Enabling brief mode Version: 0.4.0 You can enable Brief mode by configuring the [mode.brief](/config/options/options.md#mode) option in the Rsdoctor plugin. After the build, Brief mode will generate a report in the build output directory: `[outputDir]/.rsdoctor/report-rsdoctor.html`. You can view the build analysis summary by opening the HTML file in a browser. - In Brief mode, no code data is displayed to prevent the page from crashing due to large data sizes. - The report output directory and file name can be configured. Refer to: [Options](/config/options/options.md#brief). - For more configurations, refer to: [Options](/config/options/options.md#brief). ```ts title="rspack.config.js" const { RsdoctorRspackPlugin } = require('@rsdoctor/rspack-plugin'); module.exports = { // ... plugins: [ process.env.RSDOCTOR && new RsdoctorRspackPlugin({ // other options mode: 'brief', }), ].filter(Boolean), }; ``` ### Differences between brief mode and lite mode Currently, Rsdoctor has several report modes: `Normal, Brief, and Lite`. - **normal mode:** Generates a `.rsdoctor` folder in the build output directory, which contains various data files and displays code in the report page. The output directory can be configured via [reportDir](/config/options/options.md#reportdir). - **brief mode:** Generates an HTML report file in the `.rsdoctor` folder within the build output directory. All build analysis data will be consolidated and injected into this HTML file, which can be viewed by opening it in a browser. Brief mode also has additional configuration options, detailed at: [brief](/config/options/options.md#brief). - **lite mode:** Based on the normal mode, this mode does not display source code and product code, only showing the information of the bundled code. - lite mode will be deprecated in V2, refer to [lite mode deprecation notice](/config/options/options-v2.md#lite). --- url: /guide/start/cli.md --- # CLI tutorial We provide `@rsdoctor/cli` for you to use Rsdoctor's features locally through the CLI program. :::tip `@rsdoctor/webpack-plugin`, `@rsdoctor/rspack-plugin`, and `@rsdoctor/cli` should have the same major and minor versions. ::: ## Install @rsdoctor/cli :::tip - @rsdoctor/cli & @rsdoctor/webpack-plugin & @rsdoctor/rspack-plugin >= 0.1.3. - You can also use the non-installation method by using the `npx @rsdoctor/cli [options]` command. ::: ```sh [npm] npm add @rsdoctor/cli -D ``` ```sh [yarn] yarn add @rsdoctor/cli -D ``` ```sh [pnpm] pnpm add @rsdoctor/cli -D ``` ```sh [bun] bun add @rsdoctor/cli -D ``` ```sh [deno] deno add npm:@rsdoctor/cli -D ``` ## Command usage ```bash rsdoctor [options] ``` `@rsdoctor/cli` currently provides the following commands for different functionalities: ### analyze command The `analyze` command is mainly used to load the [manifest.json](/config/options/term.md) file locally and start Rsdoctor's analysis report page without the need to rebuild. ```bash rsdoctor analyze --profile ``` **Parameter Definition** - `manifestFile` is the path to the [manifest.json](/config/options/term.md) file (supports local path) **Usage Example** ```bash rsdoctor analyze --profile "./dist/.rsdoctor/manifest.json" ``` ### `bundle-diff` Command The `bundle-diff` command is used to load **two** [manifest.json](/config/options/term.md#manifestjson) files **locally** and open the Rsdoctor [Bundle Diff](/guide/usage/bundle-diff.md) page for **comparison and analysis of build bundles**. ```bash rsdoctor bundle-diff --baseline --current ``` **Parameter Definitions** - `baselineManifestJsonPath` Path to the [manifest.json](/config/options/term.md#manifestjson) used as the **baseline** (supports local paths as well as online URLs). - `currentManifestJsonPath` Path to the [manifest.json](/config/options/term.md#manifestjson) used as the **current** (supports local paths as well as online URLs) for comparison with the **baseline**. **Usage Example** ```bash rsdoctor bundle-diff --baseline="baseline/.rsdoctor/manifest.json" --current="current/.rsdoctor/manifest.json" ``` ## Node API We provide a Node.js API in `@rsdoctor/cli` that allows you to make calls during runtime in Node.js. **Importing the Module** **esm** ```js import { execute } from '@rsdoctor/cli'; ``` **cjs** ```js const { execute } = require('@rsdoctor/cli'); ``` **execute()** The `execute` asynchronous function is the execution function of Rsdoctor CLI. By calling the `execute` function, it will automatically parse [process.argv](https://nodejs.org/dist/latest-v22.x/docs/api/process.html#processargv) and invoke different commands. **execute('analyze', \{...})** If you need to directly execute the [analyze command](#analyze-command) through the Node.js API, you can call it as follows: ```ts execute('analyze', { profile: 'input the manifest.json path or url', }).then((sdk) => { console.log('execute "analyze" command success'); // you can stop the Rsdoctor's dev-server by calling the sdk'api below: // sdk.dispose(); }); ``` --- url: /guide/start/features.md --- # Features Here you can learn about the main features supported by Rsdoctor. ## Build overview | Feature | Description | Related Links | | -------------------- | ---------------------------------------------------------------------- | --------------------------------------------------- | | Project Overview | View information such as the current project configuration and version | [Project Overall](/guide/usage/project-overall.md) | | Bundle Overview | View information about the artifacts built for the current project | [Bundle Overall](/guide/usage/bundle-overall.md) | | Compilation Overview | View data information about the current project's compilation process | [Compile Overall](/guide/usage/compile-overall.md) | | Bundle Alert | The ability to perform detection based on build artifact data | [Bundle Alert](/guide/usage/bundle-alerts.md) | | Compilation Alert | The ability to perform detection based on compilation data | [Compilation Alert](/guide/usage/compile-alerts.md) | ## Compilation analysis | Feature | Description | Related Links | | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | Compilation Overview | View data information about the current project's compilation process | [Compile Overall](/guide/usage/compile-overall.md) | | Compilation Alert | The ability to perform detection based on compilation data | [Compilation Alert](/guide/usage/compile-alerts.md) | | Loader Compilation Behavior Analysis | Loader analysis data in directory and file dimensions, displaying the compilation behavior of a single file at the same time | [Loaders Analysis](/guide/usage/loaders-analysis.md) | | Loader Time Consumption Analysis | Execution sequence diagram of all Loaders in the current project | [Loaders Timeline](/guide/usage/loaders-timeline.md) | | Plugins Analysis | Data analysis of the plugins used in the project | [Plugins Analysis](/guide/usage/plugins-analysis.md) | | Resolver Analysis | Analysis data on Resolver parsing capabilities | [Resolver Analysis](/guide/usage/resolver.md) | | Loader Time Consumption Analysis and Optimization | This document describes how to use Rsdoctor to analyze and optimize build time consumption | [Loader Analysis and Optimization](/blog/topic/loader-optimization.md) | ## Bundle analysis | Feature | Description | Related Links | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | | Bundle Overview | View information about the artifacts built for the current project | [Bundle Overall](/guide/usage/bundle-overall.md) | | Bundle Alert | The ability to perform detection based on build artifact data | [Bundle Alert](/guide/usage/bundle-alerts.md) | | Bundle Analysis | Analysis of the relationships between assets, chunks, and modules in the artifact, as well as the packaged code and size analysis of each module, etc. | [Bundle Analysis](/guide/usage/bundle-size.md) | | Module Analysis | Analysis of module dependencies | [Modules Dependency Analysis](/guide/usage/module-analysis.md) | | Duplicate Packages Optimization | Inspection of duplicate dependencies used in the project | [Duplicate Packages Optimization](/blog/topic/duplicate-pkg-problem.md) | | Bundle Diff | Comparative analysis of two artifacts | [Bundle Diff](/guide/usage/bundle-diff.md) | --- url: /guide/start/intro.md --- # Introduction Rsdoctor is a build analyzer tailored for the [Rspack](https://rspack.rs/) ecosystem and fully compatible with the [webpack](https://webpack.js.org/) ecosystem. Rsdoctor is committed to being a one-stop, intelligent build analyzer that makes the build process transparent, predictable, and optimizable through visualization and smart analysis, helping development teams precisely identify bottlenecks, optimize performance, and improve engineering quality. Rsdoctor supports all tools and frameworks based on Rspack or webpack, such as: [Docusaurus](https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-rsdoctor), [Rspeedy (Lynx)](https://lynxjs.org/rspeedy/), [Storybook](https://github.com/rstackjs/storybook-rsbuild), [Next.js](https://nextjs.org/), [Nuxt](https://nuxt.com/), [Re.Pack](https://re-pack.dev/), [Modern.js](https://modernjs.dev/), [Rsbuild](https://rsbuild.rs/), [Rspress](https://rspress.rs/) and [Rslib](https://rslib.rs/). ## 🔥 Features - **Compilation Visualization**: Rsdoctor visualizes the compilation behavior and time consumption, making it easy to view build issues. - **Multiple Analysis Capabilities**: Rsdoctor supports build artifact, build-time analysis, and anti-degradation capabilities: - Build artifact support for resource lists and module dependencies, etc. - Build-time analysis supports Loader, Plugin, and Resolver building process analysis. - Build rules support duplicate package detection and ES Version Check, etc. - **Support Custom Rules**: In addition to built-in build scan rules, Rsdoctor also supports users adding custom build scan rules based on Rsdoctor's build data. ## 🛠️ Introduction ### ⭐️ Overview - The overview page (i.e., the home page) displays **project configuration, diagnostic information, compilation information, and artifact status**. ![Overall](https://assets.rspack.rs/others/assets/rsdoctor/project-overall-1.jpg) - In addition to the project overview, we also provide diagnostic modules, including compilation diagnostics and duplicate package diagnostics. If your compilation and artifacts match the diagnostic rules we defined, the corresponding warning modules will appear on the tool's home page, **where you can view the detailed reference paths of duplicate packages**: ![Overall-Alerts](https://assets.rspack.rs/others/assets/rsdoctor/overall-alerts.png) ### ⭐️ Compilation analysis Provides corresponding data and analysis functions for **Loaders, Plugins, and Module Resolve** to help you analyze problems in the compilation process. #### Loader analysis - This module mainly provides the function of data analysis such as input and output, estimated time consumption, and parameters within Rspack or webpack loaders. ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-timeline-overall.png) ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-all.png) #### Plugin analysis - This module mainly intercepts and collects data information such as the number of calls and estimated time consumption of Plugins. ![bundle](https://assets.rspack.rs/others/assets/rsdoctor/compile-plugin.jpg) #### Resolve analysis - This module mainly provides path data and estimated time consumption for module resolution in a single file within the project. Rspack temporarily does not support this module. ![bundle](https://assets.rspack.rs/others/assets/rsdoctor/resolver.png) ### ⭐️ Product analysis - In the **Bundle Size** page, we can see an overview of the product data information of the current project, as well as analyze the size and reasons for duplicate package imports. - In addition, we can also use the **Bundle Analysis** page to further analyze the relationship between the product and module in the current product, size data and other information, as well as the reasons for module introduction. ![bundle](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-overall.png) ### ⭐️ Bundle diff Using the Bundle Diff function provided by Rsdoctor, you can see the changes in resource size, duplicate packages, Packages, and other data in the artifacts, as well as the size of module files and code changes in each resource. > For more information, refer to the [Bundle Diff](/guide/usage/bundle-diff.md) documentation. | ![bundle-diff-1](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-1.png) | ![bundle-diff-2](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-2.png) | | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ## 🧑‍💻 Community Welcome to join our [Discord](https://discord.gg/wrBPBT6rkM) channel! The Rstack team and users are active there, and we're always looking for contributions. You can also join the [Feishu Group](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=3c3vca77-bfc0-4ef5-b62b-9c5c9c92f1b4) to chat with everyone. --- url: /guide/start/playground.md --- # Playground ## Introduction Playground is an online analysis tool provided by Rsdoctor that supports uploading build analysis data and viewing analysis reports online. No local installation of Rsdoctor is required to quickly experience build analysis features, with support for complete report display. ## Supported Data Formats ### 1. Rsdoctor Analysis Data Supports uploading JSON format analysis data generated by Rsdoctor to re-display complete analysis reports. #### Configuration Requirements Need to configure `output.mode: 'brief'` and set `output.options.type` to `['json']` or `['html', 'json']`: ```js title="rspack.config.mjs/webpack.config.mjs" export default { plugins: [ new RsdoctorRspackPlugin({ output: { mode: 'brief', options: { type: ['json'], // or ['html', 'json'] }, }, }), ], }; ``` - Optional configuration - `optimizationBailout`: Optional configuration. If not enabled, it will only affect the display of [Bailout Reason](/guide/usage/module-analysis.md#bailout-reason) for each Module. #### Usage Steps 1. After building the project, find the `rsdoctor-data.json` file in the output directory 2. Visit the [Playground page](https://rsdoctor.rs/preview/#/resources/uploader) 3. Upload the `rsdoctor-data.json` file 4. View the complete analysis report :::tip Difference between Brief mode and Normal mode: - **Brief mode**: Generates single files (HTML or JSON), convenient for sharing and uploading - **Normal mode**: Generates folders containing multiple files, suitable for local viewing ::: ### 2. Webpack/Rspack Stats Data Supports uploading `stats.json` files from Webpack or Rspack to automatically generate analysis reports. #### Configuration Requirements Need to configure detailed stats options to get complete build information: **Method 1: Use verbose mode** `verbose` mode outputs all build information (except debug info) and automatically includes all data required by Rsdoctor. For custom configuration, refer to the example below. See [Rspack stats](https://rspack.dev/config/stats) for detailed information. ```js title="rspack.config.mjs/webpack.config.mjs" export default { stats: 'verbose', }; ``` **Method 2: Stats configuration** Configure according to the Stats options below. ```js title="rspack.config.mjs/webpack.config.mjs" export default { stats: { all: false, chunks: true, assets: true, modules: true, chunkModules: true, hash: true, ids: true, version: true, optimizationBailout: true, // Optional configuration }, }; ``` #### Usage Steps 1. Set the above stats options in the build configuration 2. Build the project to generate the `stats.json` file 3. Visit the [Playground page](https://rsdoctor.rs/preview/#/resources/uploader) 4. Upload the `stats.json` file 5. View the automatically generated analysis report --- url: /guide/start/quick-start-shared.md --- # ## Step 2: register plugin After the dependency installation, you need to integrate the Rsdoctor plugin into your project. Below are some examples of common tools and frameworks: ### Rspack Initialize the RsdoctorRspackPlugin in the [plugins](https://www.rspack.rs/config/plugins.html#plugins) of `rspack.config.js`: ```js title="rspack.config.js" const { RsdoctorRspackPlugin } = require('@rsdoctor/rspack-plugin'); module.exports = { // ... plugins: [ // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time. process.env.RSDOCTOR && new RsdoctorRspackPlugin({ // plugin options }), ].filter(Boolean), }; ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). ### Rsbuild Rsbuild has built-in support for Rsdoctor, so you don't need to manually register plugins. See [Rsbuild - Use Rsdoctor](https://rsbuild.rs/guide/debug/rsdoctor) for more details. ### Webpack Initialize the RsdoctorWebpackPlugin in the [plugins](https://webpack.js.org/configuration/plugins/#plugins) of `webpack.config.js`: ```js title="webpack.config.js" const { RsdoctorWebpackPlugin } = require('@rsdoctor/webpack-plugin'); module.exports = { // ... plugins: [ // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time. process.env.RSDOCTOR && new RsdoctorWebpackPlugin({ // plugin options }), ].filter(Boolean), }; ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). ### Modern.js Initialize the plugin in the [tools.rspack](https://modernjs.dev/configure/app/tools/rspack) of `modern.config.ts`: ```ts title="modern.config.ts" import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { // ... tools: { rspack(config, { appendPlugins }) { // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time. if (process.env.RSDOCTOR) { appendPlugins( new RsdoctorRspackPlugin({ // plugin options }), ); } }, }, }; ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). :::tip For projects using Modern.js's webpack mode, please register the `RsdoctorWebpackPlugin` plugin through [tools.webpack](https://modernjs.dev/configure/app/tools/webpack). ::: ### Next.js #### Step 1: Register the Rsdoctor plugin Initialize the [RsdoctorRspackPlugin](#rspack-projects)([RsdoctorWebpackPlugin](#webpack-projects)) plugin in the [Rspack Config](https://rspack.rs/guide/tech/next)([webpack config](https://nextjs.org/docs/pages/api-reference/config/next-config-js/webpack)) of `next.config.ts`. **Rspack** ```ts title="next.config.ts" import type { NextConfig } from 'next'; import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; const nextConfig: NextConfig = { /* config options here */ webpack: (config) => { if (config.name === 'client') { config.plugins.push( new RsdoctorRspackPlugin({ disableClientServer: true, }), ); } else if (config.name === 'server') { config.plugins.push( new RsdoctorRspackPlugin({ disableClientServer: true, output: { reportDir: './.next/server', }, }), ); } return config; }, }; export default nextConfig; ``` **webpack** ```ts title="next.config.ts" import type { NextConfig } from 'next'; import { RsdoctorWebpackPlugin } from '@rsdoctor/webpack-plugin'; const nextConfig: NextConfig = { /* config options here */ webpack: (config) => { if (config.name === 'client') { config.plugins.push( new RsdoctorWebpackPlugin({ disableClientServer: true, }), ); } else if (config.name === 'server') { config.plugins.push( new RsdoctorWebpackPlugin({ disableClientServer: true, output: { reportDir: './.next/server', }, }), ); } return config; }, }; export default nextConfig; ``` - **Options:** The plugin provides some configuration options, please refer to [Options](/config/options/options.md). #### Step 2: Execute build Execute the **build** command, Rsdoctor will generate the corresponding report data in the local repository artifacts. ```sh [npm] npm run build ``` ```sh [yarn] yarn run build ``` ```sh [pnpm] pnpm run build ``` ```sh [bun] bun run build ``` ```sh [deno] deno run npm:build ``` #### Step 3: Open the report After installing [@rsdoctor/cli](/guide/start/cli.md), add the following scripts commands to **package.json**, executing **client:rsd** or **server:rsd** can open the report of the corresponding builder: ```sh [npm] npm add @rsdoctor/cli -D ``` ```sh [yarn] yarn add @rsdoctor/cli -D ``` ```sh [pnpm] pnpm add @rsdoctor/cli -D ``` ```sh [bun] bun add @rsdoctor/cli -D ``` ```sh [deno] deno add npm:@rsdoctor/cli -D ``` ```ts "scripts": { "client:rsd": "rsdoctor analyze --profile .next/.rsdoctor/manifest.json", // Rsdoctor's client report "server:rsd": "rsdoctor analyze --profile .next/server/.rsdoctor/manifest.json" // Rsdoctor's server report } ``` #### 📢 Note for Next.js After Next.js finishes executing the `build` command, it will terminate the terminal service, causing the report page server run by Rsdoctor during the build process to close. To solve this problem, you can use [@rsdoctor/cli](/guide/start/cli.md) to reopen the report page without re-executing the build operation. The specific method is shown in the [third step](#step-3-open-the-report) or by locally executing the rsdoctor command: For example, if Rsdoctor's build output is located at the path `.next/server/chunks/.rsdoctor/manifest.json`, you can open the report page by executing the following command: ```bash rsdoctor analyze --profile .next/server/chunks/.rsdoctor/manifest.json ``` ### Vue project Initialize the `@rsdoctor/webpack-plugin` or `@rsdoctor/rspack-plugin` plugin in the configuration file. Here is an example using `rsbuild`: ```ts title="rsbuild.config.ts" import { defineConfig } from '@rsbuild/core'; import { pluginVue } from '@rsbuild/plugin-vue'; import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default defineConfig({ plugins: [pluginVue()], performance: { buildCache: false, }, tools: { bundlerChain: (chain, { CHAIN_ID }) => { chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { // plugin options }, ]); }, }, }); ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). *** ## Step 3: Execute build Now, you can run the **build** command in the project. After the build is complete, Rsdoctor will automatically open the analysis page of this build. ```bash # Enable Rsdoctor RSDOCTOR=true npm run build # Disable Rsdoctor npm run build ``` :::tip The Rsdoctor plugin provides some configurations, please refer to [Options](/config/options/options.md). ::: --- url: /guide/start/quick-start.md --- # Quick start This document will explain how to access the Rsdoctor ability. ## Step 1: install dependencies ### Rspack projects For projects based on Rspack, such as Rsbuild or Rslib, install the following dependencies: ```sh [npm] npm add @rsdoctor/rspack-plugin -D ``` ```sh [yarn] yarn add @rsdoctor/rspack-plugin -D ``` ```sh [pnpm] pnpm add @rsdoctor/rspack-plugin -D ``` ```sh [bun] bun add @rsdoctor/rspack-plugin -D ``` ```sh [deno] deno add npm:@rsdoctor/rspack-plugin -D ``` ### Webpack projects :::tip Rsdoctor only supports webpack >= 5. ::: For projects based on webpack, install the following dependencies: ```sh [npm] npm add @rsdoctor/webpack-plugin -D ``` ```sh [yarn] yarn add @rsdoctor/webpack-plugin -D ``` ```sh [pnpm] pnpm add @rsdoctor/webpack-plugin -D ``` ```sh [bun] bun add @rsdoctor/webpack-plugin -D ``` ```sh [deno] deno add npm:@rsdoctor/webpack-plugin -D ``` *** ## Step 2: register plugin After the dependency installation, you need to integrate the Rsdoctor plugin into your project. Below are some examples of common tools and frameworks: ### Rspack Initialize the RsdoctorRspackPlugin in the [plugins](https://www.rspack.rs/config/plugins.html#plugins) of `rspack.config.js`: ```js title="rspack.config.js" const { RsdoctorRspackPlugin } = require('@rsdoctor/rspack-plugin'); module.exports = { // ... plugins: [ // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time. process.env.RSDOCTOR && new RsdoctorRspackPlugin({ // plugin options }), ].filter(Boolean), }; ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). ### Rsbuild Rsbuild has built-in support for Rsdoctor, so you don't need to manually register plugins. See [Rsbuild - Use Rsdoctor](https://rsbuild.rs/guide/debug/rsdoctor) for more details. ### Webpack Initialize the RsdoctorWebpackPlugin in the [plugins](https://webpack.js.org/configuration/plugins/#plugins) of `webpack.config.js`: ```js title="webpack.config.js" const { RsdoctorWebpackPlugin } = require('@rsdoctor/webpack-plugin'); module.exports = { // ... plugins: [ // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time. process.env.RSDOCTOR && new RsdoctorWebpackPlugin({ // plugin options }), ].filter(Boolean), }; ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). ### Modern.js Initialize the plugin in the [tools.rspack](https://modernjs.dev/configure/app/tools/rspack) of `modern.config.ts`: ```ts title="modern.config.ts" import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { // ... tools: { rspack(config, { appendPlugins }) { // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time. if (process.env.RSDOCTOR) { appendPlugins( new RsdoctorRspackPlugin({ // plugin options }), ); } }, }, }; ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). :::tip For projects using Modern.js's webpack mode, please register the `RsdoctorWebpackPlugin` plugin through [tools.webpack](https://modernjs.dev/configure/app/tools/webpack). ::: ### Next.js #### Step 1: Register the Rsdoctor plugin Initialize the [RsdoctorRspackPlugin](#rspack-projects)([RsdoctorWebpackPlugin](#webpack-projects)) plugin in the [Rspack Config](https://rspack.rs/guide/tech/next)([webpack config](https://nextjs.org/docs/pages/api-reference/config/next-config-js/webpack)) of `next.config.ts`. **Rspack** ```ts title="next.config.ts" import type { NextConfig } from 'next'; import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; const nextConfig: NextConfig = { /* config options here */ webpack: (config) => { if (config.name === 'client') { config.plugins.push( new RsdoctorRspackPlugin({ disableClientServer: true, }), ); } else if (config.name === 'server') { config.plugins.push( new RsdoctorRspackPlugin({ disableClientServer: true, output: { reportDir: './.next/server', }, }), ); } return config; }, }; export default nextConfig; ``` **webpack** ```ts title="next.config.ts" import type { NextConfig } from 'next'; import { RsdoctorWebpackPlugin } from '@rsdoctor/webpack-plugin'; const nextConfig: NextConfig = { /* config options here */ webpack: (config) => { if (config.name === 'client') { config.plugins.push( new RsdoctorWebpackPlugin({ disableClientServer: true, }), ); } else if (config.name === 'server') { config.plugins.push( new RsdoctorWebpackPlugin({ disableClientServer: true, output: { reportDir: './.next/server', }, }), ); } return config; }, }; export default nextConfig; ``` - **Options:** The plugin provides some configuration options, please refer to [Options](/config/options/options.md). #### Step 2: Execute build Execute the **build** command, Rsdoctor will generate the corresponding report data in the local repository artifacts. ```sh [npm] npm run build ``` ```sh [yarn] yarn run build ``` ```sh [pnpm] pnpm run build ``` ```sh [bun] bun run build ``` ```sh [deno] deno run npm:build ``` #### Step 3: Open the report After installing [@rsdoctor/cli](/guide/start/cli.md), add the following scripts commands to **package.json**, executing **client:rsd** or **server:rsd** can open the report of the corresponding builder: ```sh [npm] npm add @rsdoctor/cli -D ``` ```sh [yarn] yarn add @rsdoctor/cli -D ``` ```sh [pnpm] pnpm add @rsdoctor/cli -D ``` ```sh [bun] bun add @rsdoctor/cli -D ``` ```sh [deno] deno add npm:@rsdoctor/cli -D ``` ```ts "scripts": { "client:rsd": "rsdoctor analyze --profile .next/.rsdoctor/manifest.json", // Rsdoctor's client report "server:rsd": "rsdoctor analyze --profile .next/server/.rsdoctor/manifest.json" // Rsdoctor's server report } ``` #### 📢 Note for Next.js After Next.js finishes executing the `build` command, it will terminate the terminal service, causing the report page server run by Rsdoctor during the build process to close. To solve this problem, you can use [@rsdoctor/cli](/guide/start/cli.md) to reopen the report page without re-executing the build operation. The specific method is shown in the [third step](#step-3-open-the-report) or by locally executing the rsdoctor command: For example, if Rsdoctor's build output is located at the path `.next/server/chunks/.rsdoctor/manifest.json`, you can open the report page by executing the following command: ```bash rsdoctor analyze --profile .next/server/chunks/.rsdoctor/manifest.json ``` ### Vue project Initialize the `@rsdoctor/webpack-plugin` or `@rsdoctor/rspack-plugin` plugin in the configuration file. Here is an example using `rsbuild`: ```ts title="rsbuild.config.ts" import { defineConfig } from '@rsbuild/core'; import { pluginVue } from '@rsbuild/plugin-vue'; import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default defineConfig({ plugins: [pluginVue()], performance: { buildCache: false, }, tools: { bundlerChain: (chain, { CHAIN_ID }) => { chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { // plugin options }, ]); }, }, }); ``` - **Options:** The plugin provides some configurations, please refer to [Options](/config/options/options.md). *** ## Step 3: Execute build Now, you can run the **build** command in the project. After the build is complete, Rsdoctor will automatically open the analysis page of this build. ```bash # Enable Rsdoctor RSDOCTOR=true npm run build # Disable Rsdoctor npm run build ``` :::tip The Rsdoctor plugin provides some configurations, please refer to [Options](/config/options/options.md). ::: --- url: /guide/usage/bundle-alerts.md --- # Bundle alerts ## Introduction The `Alerts` section in the `Overall` page is used to display the results of "Build Rules" and "Compilation Rules", as shown in the image below. In addition to being displayed on the page, the rules will also be displayed in the terminal log. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-alerts.png) You can check the built-in rules for bundle alerts below to understand the details of each rule. ### Built-in Rules 1. [\[E1001\] Duplicate Packages](/guide/rules/rules.md#e1001-duplicate-packages) 2. [\[E1002\] Cross Chunks Package](/guide/rules/rules.md#e1002-cross-chunks-package) 3. [\[E1004\] ECMA Version Check](/guide/rules/rules.md#e1004-ecma-version-check) For more details, please refer to the [Built-in Rules](/guide/rules/rules.md). --- url: /guide/usage/bundle-diff.md --- # Bundle diff Version: 0.4.5 We provide the Bundle Diff feature, which allows you to compare and analyze the changes between two build bundles. Currently, we offer the following usage methods: - [Open locally with CLI](/guide/start/cli.md) - Online upload analysis (planned support) ## Usage ### Open locally with CLI First, you need to prepare **2 copies** of the [manifest.json](/config/options/term.md#manifestjson) produced by Rsdoctor. Then, install [@rsdoctor/cli](/guide/start/cli.md#cli-tutorial) and use the CLI command `bundle-diff`. For detailed command usage, see [command usage tutorial](/guide/start/cli.md#bundle-diff-command). ### Online upload analysis (planned support) We plan to provide an online page for Bundle Diff analysis. You can upload **2 copies** of the [manifest.json](/config/options/term.md#manifestjson) produced by Rsdoctor on the page, one as the Baseline and the other as the Current. By clicking Start Diff, you can enter our analysis page. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff.png) ## User guide ### Feature overview In the Bundle Diff module, you can see the comparison of information between the two build bundles, including: - **total size changes** - **size changes of different file types** - **initial bundles size changes** - **changes in the number of duplicate packages** - **changes in the number of NPM Packages**, and more. In addition to the above data overview, we can also perform more in-depth data query and analysis through the **details list** module at the bottom of the page. ### Terminology | Term | Description | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Baseline | Represents the **reference data source** | | Current | Represents the **target data source** to be compared with the Baseline | | Asset / Assets | Represents the **build files** | | Bundle Size | Represents the **total size** of all files in the build | | Total JS | Represents the total size of all `.js` files in the build | | Initial JS | Represents the total size of all **first screen** `.js` files in the build | | Total CSS | Represents the total size of all `.css` files in the build | | Initial CSS | Represents the total size of all **first screen** `.css` files in the build | | Image | Represents the total size of all `.png`/`.jpg`/`.svg`/`.webp`/`.jpeg`/`.gif`/`.bmp` files in the build | | Font | Represents the total size of all `.ttf`/`.fnt`/`.fon`/`.otf` files in the build | | Media | Represents the total size of all `.mp3`/`.mp4`/`.avi`/`.wav`/`.flv`/`.mov`/`.mpg`/`.mpeg` files in the build | | HTML | Represents the total size of all `.html` files in the build | | Duplicate Packages | Represents the **total number of duplicate packages** in the build | | Modules | Represents the total number of modules in the build | | Packages | Represents the total number of **NPM Packages** in the build | | New | Represents **newly added** items, i.e., **not present in Baseline but present in Current** | | Deleted | Represents **removed** items, i.e., **present in Baseline but not in Current** | | Changed | Represents items that **only changed in content**, i.e., **present in both Baseline and Current but with content changes** | | Parsed Size | Represents the **final size** of the build bundles | ### Instructions #### Dashboard At the top of the page, we can see many data points composed of different cards, including the following information: - **Bundle Size** includes the total size of the two builds and the change rate. - **Total JS | Initial JS** includes the total size and change rate of all JS and first screen JS in the two builds. - **Total CSS | Initial CSS** includes the total size and change rate of all CSS and first screen CSS in the two builds. - **Image | Font | Media** includes the size and change rate of image, font, and media files. - **HTML** includes the size and change rate of HTML files. - **Others** represents the size and change rate of all other files not mentioned above. - **Duplicate Package** represents the number of duplicate packages in the two builds. Clicking on it allows you to view the details of the duplicate packages. - **Modules** represents the number of modules in the two builds. - **Packages** represents the total number of NPM Packages in the two builds, as well as the number of new, deleted, and changed packages. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-cards.png) #### Overview In the Overview module, we can see the **size**, **quantity**, and **change rate** of different **file types**. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-all.png) #### Assets :::tip When displaying Asset names, Rsdoctor tries to remove the hash values from the build file names to facilitate comparison. ::: In the Assets module, we can see the **size** and **change rate** of the build files. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-assets-list.png) By **clicking** the **"+" button** in front of the list items, you can expand to see the **list of modules** contained in the corresponding Asset (i.e., `Modules of "***"`), which shows the **size** and **change rate** of the modules. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-assets.png) Rsdoctor is compatible with the situation where Assets files have **the same name but different hashes**. However, for Assets with **different names generated by splitting packages**, Rsdoctor cannot identify their comparison objects. Therefore, the Rsdoctor Assets module also provides a select component, allowing you to **manually select the Assets resources you want to compare**. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-select-assets.png) #### Modules In the Modules module, we can see the **name**, **size**, and **change rate** of all modules contained in the two builds. The `New` / `Deleted` / `Changed` tags indicate whether the module is newly added, deleted, or just changed in the `Current` build. The `node_modules` tag indicates that the module's path contains `/node_modules/`. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-module-list.png) On the right side of the list items, you can view the module code changes by clicking the corresponding "View Changes" button. **Code comparison includes several types of data:** - **Source Code: Source code data.** Available in `Normal` mode, not available in `Lite` mode, and not available in `Brief` mode. - **Bundled Code: Built code.** Available in `Normal` mode, available in `Lite` mode, and not available in `Brief` mode. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-module-changes.png) #### Packages In the Packages module, we can see the **list of all NPM Packages** contained in the two builds. Each list item includes the **Package Name**, **Version**, and **Parsed Size** (final size after packaging). ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-packages.png) --- url: /guide/usage/bundle-overall.md --- # Bundle overall ## Overview On the homepage of **Rsdoctor**, we can see a card called `Bundle Overall`, which provides information about the **build artifacts** of the current project. The content is shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-overall-1.png) ## Glossary | Term | Description | | -------------------------------- | -------------------------------------------------------------------------------------------- | | total files | Represents the total number of files in the artifacts | | total size | Represents the total size of all files in the artifacts | | js files | Represents the number of `.js` files in the artifacts | | css files | Represents the number of `.css` files in the artifacts | | image files | Represents the number of `.png`/`.jpg`/`.svg`/`.webp`/`.jpeg`/`.gif`/`.bmp` files | | font files | Represents the number of `.ttf`/`.fnt`/`.fon`/`.otf`/`.woff`/`.woff2` files in the artifacts | | media files | Represents the number of `.mp3`/`.mp4`/`.avi`/`.wav`/`.flv`/`.mov`/`.mpg`/`.mpeg` files | | html files | Represents the number of `.html` files in the artifacts | | modules | Represents the total number of modules in the artifacts | | duplicate packages | Represents the total number of duplicate packages in the artifacts | ## Usage instructions ### View bundle artifacts - The **"TOTAL Size"** data on the card represents the total size of the project. Clicking on this number will navigate to the [Bundle Size](/guide/usage/bundle-size.md) - The card also displays the number and total size of different file types. Clicking on the corresponding blue icon will display the list of files, as shown in the following image: - **Initial:** Refers to the Chunk being the main chunk of the entry. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-overall-files.png) ### [Duplicate Packages](/blog/topic/duplicate-pkg-problem.md) If the `Duplicate Packages` number on the card is greater than 0, you can **click to view the details of the duplicate packages**. The content is shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-overall-dup-pkg.png) Here, you can see the list of all duplicate packages detected by Rsdoctor in the current build artifacts. --- url: /guide/usage/bundle-size.md --- # Bundle analysis :::info If you want to analyze the reference chain of a specific Module, you can check 👉🏻 [Module Analysis](/guide/usage/module-analysis.md). ::: ## ⭐️ Overview **Rsdoctor** provides the `Bundle Size` module, which is mainly used to analyze the information of the build artifacts of **Webpack** or **Rspack**, including the **size of resources**, **duplicate packages**, and **module reference relationships**: - **Bundle Overview**: Displays the total number of artifacts, the number and size of each file type, as well as duplicate packages and their reference chains, 👉🏻 [**Bundle Overview**](#-bundle-overview). - **Bundle Analysis (`Bundle Analysis`) Module**: Analyzes the size and code information of the build artifacts (**Assets**) and the included **Modules**. In this module, you can view the **actual code size of modules after packaging** in the Assets, the original code of modules, **packaged code segments**, and **module reference relationships**. The **Bundle Analysis** displays two view modes, **Tree Map** and **Tree Graph**: - 👉🏻 [**Tree Map**](/guide/usage/bundle-size.md#-tree-map) Tree Map is a classic build artifact analysis view that helps developers visualize and analyze the composition of bundles more intuitively, as well as the proportion of resources (Assets) and modules (Modules). It also supports searching for module resources, and clicking on module resources can zoom in to that module area. ![](https://assets.rspack.rs/others/assets/rsdoctor/treemap-intro.gif) - 👉🏻 [**Tree Graph**](/guide/usage/bundle-size.md#-tree-graph) Tree Graph is a **file tree-based** build artifact analysis view that helps developers visualize and analyze the composition of artifacts more intuitively, as well as the proportion of artifacts (Assets) and modules (Modules). It also supports searching for module resources, and clicking on modules can view module details and code. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-overall.png) ## 🪐 Glossary - **`Assets`**: Resources are files that ultimately exist in the output folder, including JavaScript, CSS, images, fonts, media, and other file types. Each Chunk has corresponding [Assets resources](https://webpack.js.org/concepts/under-the-hood/#chunks). - **`Module`**: Multiple Modules combine to form a Chunk. For more information about Module types, please refer to [Rspack Modules](https://www.rspack.rs/api/modules.html) and [Webpack Modules](https://webpack.js.org/concepts/modules/#what-is-a-webpack-module). - **`Source Size`**: The original size of the file, before any transformations and minification. - **`Bundle Size`**: The final output size of the files. If you enabled minification, this value shows the minified size. - **`Gzip Size`**: The size of the file after gzip compression. - **`Package Count`**: The number of third-party packages. - **`Initial Chunk`**: **initial (initialization)** is the main Chunk of the entry point. This Chunk contains all the modules specified by the entry point and their dependencies, unlike the **Chunk** resources for "**on-demand loading**". - For more information about Initial Chunk, please refer to [Initial Chunk Introduction](https://webpack.js.org/concepts/under-the-hood/#chunks). - **`Duplicate Packages`**: Duplicate third-party packages bundled into the project. Excludes third-party packages that are not bundled into the artifact. Please refer to [Duplicate Packages](/guide/usage/bundle-alerts.md). - **`Concatenated Module`**: A concatenated module is a technique that combines multiple modules into one closure during packaging. In the past, Webpack would package each module into a separate closure, and this encapsulation function would cause slower execution of JavaScript in the browser. Optimization can be achieved by enabling the [`optimization.concatenateModules`](https://rspack.rs/misc/glossary#scope-hoisting) parameter. ## 🪐 Bundle overview ### Bundle information card The bundle overview displays information about the number and size of files, such as `Total Files`. Clicking on the card expands the resource details, as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-overall-1.png) - Clicking on the details icon displays the corresponding resource tree on the right, indicating the resource sizes: ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-tree.png) - Clicking on the tabs allows you to switch between different resource information views, such as **「Total JS | Initial JS」**. The card also displays the percentage, size, and number of resources. Similarly, clicking on the icon in the lower right corner expands the resource list. ### Duplicate packages - The **Duplicate Packages** card displays the number of duplicate third-party packages in the project. Clicking on the image allows you to view the specific details of the duplicate packages. Please note that these are duplicate packages that have been bundled. For more information, please refer to [Duplicate Packages](/guide/usage/bundle-alerts.md). ## 🪐 Tree map :::info If an Asset block has no Module chunks, you need to manually enable SourceMap. Note: Only enable SourceMap when Rsdoctor is enabled, do not affect production builds. [FAQ](/guide/more/faq.md#no-bundledparsed-size-for-modules-in-bundle-analysis) ::: Tree Map view can intuitively display the proportion and relationship between modules, as shown in the following image. Clicking on module resources can zoom in to that module area. ![](https://assets.rspack.rs/others/assets/rsdoctor/treemap-intro.gif) - Tree Map view also supports searching for module resources. The left sidebar can filter resources (Assets) and search for modules (Modules). Clicking on the search results for modules can zoom in to that module area. ![](https://assets.rspack.rs/others/assets/rsdoctor/treemap-all.png) - Double-clicking on a block can display its Module details card, as shown in the following image. For more information, see [Module Details](/guide/usage/module-analysis.md). ![](https://assets.rspack.rs/others/assets/rsdoctor/treemap-dbclick.png) ## 🪐 Tree graph :::info If an Asset block has no Module chunks, you need to manually enable SourceMap. Note: Only enable SourceMap when Rsdoctor is enabled, do not affect production builds. [FAQ](/guide/more/faq.md#no-bundledparsed-size-for-modules-in-bundle-analysis) ::: Tree Graph is a **file tree-based** build artifact analysis view used to analyze the size and code information of build artifact resources (**Assets**) and the included **Modules**. In this module, you can view the **actual code size of modules after packaging** in the Assets, the original code of modules, **packaged code segments**, and **module reference relationships**. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-overall.png) Click on the **"Bundle Size"** option in the navigation bar to view the Bundle analysis report. Please note that to display this page, you need to enable the build artifact analysis capability [features](/config/options/options.md). ::: tip If your project is based on Rspack and the version is lower than 0.5.1, you cannot view code information. ::: ### Resource and module relationship display The **Bundle Analysis** module is used to analyze the size and code information of the build artifacts' resources (**Assets**) and the included **Modules**. The example image is shown below: - On the left side is the list of **Assets** resources, sorted in descending order by resource size. You can click the **"expand all"** button to expand all nodes. - On the right side is the list of **Modules** corresponding to the **Assets**, also sorted in descending order by module size after packaging. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-analysis-tree.png) ### Search and filter box The top toolbar from left to right includes: the search tool for **Assets**, the filter tool for **Assets** size, and the filter tool for **Module** size. - **Search Entry Input Box**: Enter the keyword of an **Entry** in the input box to search for the corresponding **Entry** and display only the related **Assets**. - **Search Assets Input Box**: Enter the keyword of an **Assets** in the input box to search for the corresponding **Assets**. - **Assets Size Filter Tool**: Enter a number with units of KB or MB to filter out **Assets** resources smaller than the specified size. - **Module Size Filter Tool**: Enter a number with units of KB or MB to filter out **Module** resources smaller than the specified size. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-analysis-selects.png) ### Search module Module search functionality is supported. Users can click the "**Search Module**" button to open the module search dialog. By entering the module name, users can quickly locate and view the module's position in the Assets, making it easier to analyze the module's reference relationships and size. As shown in the following image, the results of matching the search Module keyword can be seen: ![](https://assets.rspack.rs/others/assets/rsdoctor/search-modules.png) ### Module tag explanation The **Assets** tag is shown in the left image, from left to right representing: **Resource Size**, **[Initial Chunk](https://webpack.js.org/concepts/under-the-hood/#chunks)**, and **Code View**. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-assets-tags.png)![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-modules-tags.png) The **Modules** tag is shown in the right image, from left to right representing: - **Bundled Size** - The final size of the module bundled into the artifact. Some modules labeled as `concatenated` are concatenated modules, which have a certain impact on this value. Please refer to the explanation of `concatenated module` below. - **[Concatenated Module](https://rspack.rs/misc/glossary#scope-hoisting)**: Concatenated modules combine multiple modules into one closure during bundling. There are two types: - One is the concatenated main module, indicating how many `Modules` are concatenated. - The other is the concatenated sub-module, indicating which `Module` it is aggregated into. This sub-module cannot be further unpacked after bundling, so the specific `Bundled Size` cannot be determined. Only the size of the entire concatenated module is known, which is marked at the end of the main module. - **Module Explorer** tag: Click to open the dependency analysis page between `Modules`. - **Code View** tag: Click to expand code segments, including `Source` (source code), `Transformed` (compiled code), and `Bundled` (bundled code). ### Support for concatenated module analysis **[Concatenated Module](https://rspack.rs/misc/glossary#scope-hoisting)** refers to multiple modules that are merged into a single closure, which cannot be analyzed through AST syntax analysis. However, concatenated modules may contain code from different packages, making the analysis of sub-modules within concatenated modules a key focus, especially for projects using the ["all-in-one"](https://rsbuild.rs/guide/optimization/code-splitting#all-in-one) bundling approach. Rsdoctor supports the analyze of **[Concatenated Module](https://rspack.rs/misc/glossary#scope-hoisting)** and accurately calculates the real bundled size of sub-modules within concatenated modules, helping developers accurately identify the actual build size after Tree Shaking, analyze the impact of merged modules on final bundle size, and optimize code splitting strategies. - **For Rspack projects**: The Rsdoctor native plugin built into Rspack (>=1.4.11) has enhanced sourcemap capabilities, allowing seamless analysis of concatenated modules without enabling source maps. > As shown in the figure below, this is the analysis of 'all-in-one' bundling. The first image shows the previous inability to analyze, while the second image shows the analyzable situation. - Not support concatenated module ![](https://assets.rspack.rs/others/assets/rsdoctor/all-in-one-before.png) - Support concatenated module ![](https://assets.rspack.rs/others/assets/rsdoctor/all-in-one-after.png) - **For webpack projects**: Source maps must be enabled to accurately decompose and analyze concatenated modules, as shown in the following configuration. ```js export default { // ... devtool: 'cheap-source-map', // or other devtool configuration }; ``` - Rsdoctor supports the following SourceMap configurations for Concatenated Module analysis: - source-map - hidden-source-map - inline-source-map - cheap-source-map - cheap-module-source-map - nosources-source-map ## 🪐 Module details Click the module tag to view module details, as shown below: ![](https://assets.rspack.rs/others/assets/rsdoctor/bailout-reason.gif) - **Reasons**: As the name suggests, it means the \[reason] why a Module exists. Reasons indicate which Modules import this Module, and the entire Reasons Tree shows the upstream reference chain of this Module, including both direct and indirect parents. This corresponds to Rspack's stats.reasons. - **Dependencies**: The Modules that this Module depends on. - **Bailout Reason**: The reason why this Module failed Tree Shaking. > For more details, see: [Module details](/guide/usage/module-analysis.md) ## 🪐 Supports bannerPlugin :::danger `supports.banner` option is only used for debugging, do not use it in production. ::: Both Rspack and webpack support the [BannerPlugin](https://www.rspack.rs/plugins/webpack/banner-plugin#bannerplugin), which is a built-in plugin that allows you to add specific content at the top or bottom of the generated chunks. The added code segment will affect the analysis capability of the bundle. Rsdoctor is compatible with the logic of adding code using the BannerPlugin, but it is not enabled by default because Rsdoctor needs to add tag code. The Rsdoctor BannerPlugin capability is enabled in the following two cases: 1. The project uses the BannerPlugin in `rspack.config.(js|ts)` or `webpack.config.(js|ts)`. 2. Enable Rsdoctor BannerPlugin capability through Rsdoctor options by setting `supports.banner`: ```ts new RsdoctorRspackPlugin({ supports: { banner: true, }, }); ``` --- url: /guide/usage/compile-alerts.md --- # Compile alerts We have integrated some capabilities based on compilation data detection. If the current compilation result contains data that hits the rules we define, the `Compile Alerts` module will appear at the bottom of the **Rsdoctor** main interface, as shown in the image below: ![](https://assets.rspack.rs/others/assets/rsdoctor/compile-alerts.png) This module allows us to visually see some warning information about our project's compilation, which can help us further optimize the project's compilation performance. ## Rules The current compilation rules include: :::tip [Rule List](/guide/more/rules.md) ::: - `E1003` Loader Performance Check. [\[E1003\] Loader Performance Optimization](/guide/rules/rules.md#e1003-loader-performance-optimization) - `E1005` Default Import Check. [\[E1005\] Default Import Check](/guide/rules/rules.md#e1005-default-import-check) --- url: /guide/usage/compile-overall.md --- # Compile overall ## Overview On the homepage of **Rsdoctor**, there is a card called `Compile Overall` that provides information about the **compilation process** of the current project. The content is shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/compile-overall-1.jpg) :::tip For each compilation phase, if the time data is displayed in blue , it means that you can click to view the detailed time breakdown . ::: ## Glossary The following table explains the meaning and code implementation of each phase in the card: | Phase Name | Description | Code Implementation | | ---------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Bootstrap -> BeforeCompile | Represents the time taken from project startup to before compilation starts |
  • Reports [process.uptime()](https://nodejs.org/dist/latest-v22.x/docs/api/process.html#processuptime) as the duration when **compiler.hooks.beforeCompile** is called
| | Compile | Represents the total time taken for the project compilation |
  • The start time is the time when **compiler.hooks.beforeCompile** is called, and the end time is the time when **compiler.hooks.afterCompile** is called
| | AfterCompile -> Done | Represents the time taken from compilation completion to the end of the entire process |
  • The start time is the time when **compiler.hooks.afterCompile** is called, and the end time is the time when **compiler.hooks.done** is called
| | Minify | Represents the time taken for file compression during the compilation process in most cases |
  • Calculates the sum of the time taken for each call of **compilation.hooks.optimizeChunkAssets** and **compilation.hooks.processAssets**
| ## Usage instructions ### Bootstrap -> BeforeCompile details By **clicking on the data of the `Bootstrap -> BeforeCompile` phase**, a popup will appear on the page, as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/compile-overall-boostrap.jpg) The popup mainly contains a chart: - The **x-axis** represents **time** - The **y-axis** represents all the **hooks** that have been **tapped by plugins** before the **compiler.hooks.beforeCompile** is called - The data in the chart represents the **start and end time** of each **hook**. Hovering over a data point in the chart will display the following information in a tooltip: - **hook**: the name of the hook - **tap name**: the name value when [.tap](https://github.com/webpack/tapable#hookhookmap-interface) is called - **start**: the start time - **end**: the end time - **duration**: the duration, calculated as `end - start` ### Compile phase In this section, you can navigate to "Compile Analysis" -> "Loader Analysis" -> [**"Loader Timeline"**](/guide/usage/loaders-timeline.md) in the navigation bar to view the timeline of loader compilation time. ### AfterCompile -> done details By **clicking on the data of the `AfterCompile -> Done` phase**, a popup will appear on the page, as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/compile-overall-aftercompile-1.jpg) The popup mainly contains a data table that shows the relevant data of the calls. The field meanings are as follows: - **Plugin Tap Name**: the name value when [.tap](https://github.com/webpack/tapable#hookhookmap-interface) is called - **Hook**: the name of the hook - **calls**: the number of times the hook is called - **duration(total)**: the total time of all the calls Scrolling down the page will show the corresponding chart: ![](https://assets.rspack.rs/others/assets/rsdoctor/compile-overall-aftercompile-2.jpg) The chart shows: - The **x-axis** represents **time** - The **y-axis** represents all the **hooks** that have been **tapped by plugins** between **compiler.hooks.afterCompile** and **compiler.hooks.done** - The data in the chart represents the **start and end time** of each **hook**. Hovering over a data point in the chart will display the following information in a tooltip: - **hook**: the name of the hook - **tap name**: the name value when [.tap](https://github.com/webpack/tapable#hookhookmap-interface) is called - **start**: the start time - **end**: the end time - **duration**: the duration, calculated as `end - start` ### Minify details :::tip Minify details are currently not available for Rspack projects. ::: By **clicking on the data of the `Minify` phase**, a popup will appear on the page, as shown in the following images: | | | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | The content in the popup has similar meanings to the previous paragraphs, so it will not be repeated here. ## Reference documentation - [**Rspack Hooks**](https://www.rspack.rs/api/plugin-api.html#beforecompile) - [**Webpack Hooks**](https://webpack.js.org/api/compilation-hooks/) --- url: /guide/usage/loaders-analysis.md --- # Loaders analysis **Rsdoctor** provides the `Loader Analysis` module, which mainly provides statistics on Loaders at the **directory and file level**. It helps you analyze the compilation of **folders** and **individual files** by Loaders. Click on the navigation bar **"Compile Analysis"** -> **"Loader Analysis"** option to view the compilation analysis report. Of course, this page will only display the features if the `loader` analysis capability is enabled [features](/config/options/options.md). ## Overview Firstly, in this module, you can directly see the file tree structure of all files processed by Loaders, as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-all.png) In the **filter search box** at the top, you can filter Loaders and search for file names. After entering the name, the file tree dynamically displays the matching files, making it easier to locate the files you want to query. In the file tree structure below, there are two interactive forms to obtain different data information: - **Clicking on a directory**: Displays **Loader data for the file directory**. - **Clicking on a file**: Displays **detailed Loader information for the individual file**. The corresponding details will be explained in the following paragraphs. ## Loader data for file directories By **clicking on a selected directory**, you can see the **time statistics of all Loaders in the selected directory** ([estimated time consumption](/guide/more/faq.md#loader-time-consuming-data-is-inaccurate)) on the right side of the file tree. The content of the "Statistics of \*\*\*" card is shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-table.png) Here are the main information we can obtain: - The number of **files processed** and the **estimated time consumption** for an **individual Loader** in the selected directory. - The number of **files processed** and the **estimated time consumption** for **all Loaders** in the selected directory. Usually, we can select some **third-party library directories** within `node_modules` and then determine whether it is necessary to set [module.rule.exclude](https://webpack.js.org/configuration/module/#ruleexclude) for this directory based on the Loader's time consumption information. This helps reduce the processing time of common Loaders like `babel-loader`. If it is a third-party library with **advanced ES syntax** or a package within the **workspace**, we need to make more granular decisions at the individual file level based on the content in the next paragraph to optimize Loader performance. ## Loader details for individual files By **clicking on a file**, a modal will appear with the following content: - "**Left section**": A list of all **executed Loaders** for the clicked file and the **time consumption** of each Loader for compiling the file. - "**Right section**": Information about the **input, output**, and **parameter data** of the selected Loader at the time of invocation. ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-code-change.png) - **Parameter Data**: Click on "**show more**" or the expand button in the top left corner to view the corresponding parameter information. ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-options.png) As shown in the image, we can obtain the following information about the **target file**: - All the Loaders it has gone through. - The **parameter data** on the [**Loader Context**](https://webpack.js.org/api/loaders/#the-loader-context). - The input and output of the Loader. --- url: /guide/usage/loaders-timeline.md --- # Loaders timeline ## Overview By clicking on the "Compile Analysis" -> "Loader Analysis" option in the navigation bar of **Rsdoctor**, we can see the **execution timeline** of all loaders in the current project. Please note that this page requires the `loader` analysis capability to be enabled in order to display the [features](/config/options/options.md). The content of this page is shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-timeline-overall.png) ## Glossary The fields in the chart on the page have the following meanings: | Term | Description | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | | files | Represents the **total number of files** processed by the loader | | files(node\_modules) | Represents the number of files processed by the loader within `node_modules` | | files(outside the cwd) | Represents the number of files processed by the loader outside of the `cwd` | | duration | Represents the **estimated time** taken by the loader to execute | | start(min) | Represents the **earliest start time** among all the data of the loader | | end(max) | Represents the **latest end time** among all the data of the loader | | isPitch | Represents whether the loader execution is a [pitch](https://webpack.js.org/api/loaders/#pitching-loader) function or not | | filepath | Represents the **file path** received by the loader | | start | Represents the **start time** of the loader execution | | end | Represents the **end time** of the loader execution | ## Usage In the **Loaders Timeline**, the **left Y-axis** represents the **loader names**, while the **top X-axis** corresponds to **time (hour:minute:second)**. We can use the zoom feature and hover over the chart to view more detailed information about loader invocations. There are two selector at the top of the page, where you can enter the **Loaders** or **Files** you want to filter, and the timeline chart will be displayed based on the filtered content. ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-timeline-overall.png) ### Viewing overall loader information If we want to view the **summary of all data** for a single loader, we can hover over the position shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-timeline-loader-timeline.png) At this point, we can see the **summary of all invocations** within a single loader (refer to the [Glossary](#glossary) for field definitions), as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-timeline-loader-card.png) ### Viewing individual loader invocation information If we want to view the **information of a single invocation** for a loader, we can hover over any **colored stripe** within the position shown in the following image. At this point, we can see the **information of the current invocation** within a single loader (refer to the [Glossary](#glossary) for field definitions), as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-timeline-loader-file.png) --- url: /guide/usage/mcp.md --- # MCP Server ## Introduction @rsdoctor/mcp-server is an MCP Server tool designed to help users more conveniently utilize Rsdoctor's build data. It works with Rsdoctor's local build analysis data and helps you quickly obtain build analysis results through a Q\&A interface. ## Core features **@rsdoctor/mcp-server** provides four core analysis capabilities: - **Bundle Analysis**: Analyzes bundle size, composition and other information - **Dependency Analysis**: Analyzes project dependency relationships, duplicate dependencies, and Tree Shaking issues. - **Bundle Optimization Suggestions**: Provides suggestions for bundle size optimization and code splitting - **Compilation Optimization Suggestions**: Analyzes compilation time and provides compilation performance optimization suggestions ## Usage examples ### 1. Bundle optimization analysis By asking "Please help me to optimize the bundle or artifacts", the tool will analyze the build output and provide optimization suggestions. Example video: ### 2. Dependency analysis By asking "Please investigate the referrer dependency of node\_modules/dayjs/index.js", the tool will analyze the dependency relationships of the specified module. Example video: ### 3. Compilation performance analysis By asking "Please help me find files or loaders with high compilation time and provide optimization suggestions", the tool will analyze compilation time and provide optimization suggestions. Example video: ### 4. Tree Shaking Issues By asking "Please help me to check why react-dom/client.js can not be tree-shaken?", the tool will help analyze why this module cannot be tree-shaken. > Note: Please use Rsdoctor plugin version 1.1.5 or above. ![tree-shaking](https://assets.rspack.rs/others/assets/rsdoctor/tree-shake-mcp.png) ## Quick start ### 💡 Version requirements :::warning The following Rsdoctor plugin versions are required: - @rsdoctor/rspack-plugin >= 1.1.2 - @rsdoctor/webpack-plugin >= 1.1.2 Note: Please ensure you are using the latest version for the best experience. ::: ### 1. Plugin configuration If you haven't added the Rsdoctor plugin yet, you need to configure it in your project. [👉🏻 Quick Start](https://rsdoctor.rs/guide/start/quick-start). ### 2. Enable Rsdoctor and run local build Enable Rsdoctor and run the build. **Do not use MCP Client to start the project, as Rsdoctor's local service will block the MCP Client's dialogue process**. ```bash # Enable Rsdoctor RSDOCTOR=true npm run build ``` - Note: If `disableClientServer: true` is configured, it needs to be modified to `disableClientServer: false`, and `disableClientServer` defaults to false. ### 3. Start MCP Server #### Cursor [![Add Rsdoctor MCP server to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](cursor://anysphere.cursor-deeplink/mcp/install?name=rsdoctor&config=eyJjb21tYW5kIjoibnB4IC15IEByc2RvY3Rvci9tY3Atc2VydmVyQGxhdGVzdCJ9) 1. Create a `.cursor/mcp.json` file in the project root directory: ```json { "mcpServers": { "rsdoctor": { "command": "npx", "args": ["-y", "@rsdoctor/mcp-server@latest"] } } } ``` 2. Restart the Cursor editor 3. Start interaction in the MCP panel #### VS Code / GitHub Copilot [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_Rsdoctor_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=ffffff)](vscode:mcp/install?%7B%22name%22%3A%22rsdoctor%22%2C%22type%22%3A%22stdio%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40rsdoctor%2Fmcp-server%40latest%22%5D%7D) 1. Create `.vscode/mcp.json` in your project root directory. GitHub Copilot will automatically load the MCP Server configuration. ```json { "mcpServers": { "rsdoctor": { "command": "npx", "args": ["-y", "@rsdoctor/mcp-server@latest"] } } } ``` 2. In the Copilot Chat view, select [Agent mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode#_use-agent-mode), then start interacting. #### Claude Add configuration in `claude_desktop_config.json`: ```json { "mcpServers": { "rsdoctor": { "command": "npx", "args": ["-y", "@rsdoctor/mcp-server@latest"] } } } ``` #### Cline Add configuration in the configuration file: ```json { "mcpServers": { "rsdoctor": { "command": "npx", "args": ["-y", "@rsdoctor/mcp-server@latest"] } } } ``` #### Trae You can configure and add it via "Create Agent" → "MCP" → "Add" → "Manual Add": ```json { "mcpServers": { "rsdoctor": { "command": "npx", "args": ["-y", "@rsdoctor/mcp-server@latest"] } } } ``` ## Configuration instructions ### Command line parameters | Parameter | Description | Default | Example | | ---------- | ------------------------------------------- | ------------------------------------------------------------- | ---------------- | | `compiler` | Specify the name of the compiler to analyze | Automatically detected | `--compiler web` | | `port` | Specify the MCP Server port | Latest port number (written to ` ~/.cache/rsdoctor/mcp.json`) | `--port 1000` | ### Multi-compiler project configuration In a multi-compiler project, each compiler will have a separate Rsdoctor build analysis data. Use the `--compiler` parameter to specify the compiler to analyze: ```bash npx @rsdoctor/mcp-server@latest --compiler web ``` ### Port configuration 1. Configure the MCP Server port: ```bash npx @rsdoctor/mcp-server@latest --port 1000 ``` 2. Configure the Rsdoctor local service port: ```js new RsdoctorRspackPlugin({ port: 9988, }); ``` ## Tools list ### Product analysis tool | Tool | Description | Parameters | | ------------------------ | ------------------------------------------- | ---------------- | | `get_chunks` | Get all code block information | - | | `get_chunk_by_id` | Get specific code block information | chunkId (Number) | | `get_large_chunks` | Get code blocks with large volume | - | | `get_media_asset_prompt` | Get media resource optimization suggestions | - | ### Dependency analysis tool | Tool | Description | Parameters | | -------------------------- | -------------------------- | ------------------- | | `get_modules` | Get all module information | - | | `get_module_by_id` | Get module information | moduleId (Number) | | `get_module_by_path` | Get module by path | modulePath (String) | | `get_module_issuer_path` | Get module source path | moduleId (String) | | `get_package_info` | Get package information | - | | `get_package_dependencies` | Get dependency list | - | | `get_duplicate_packages` | Get duplicate package list | - | | `get_similar_packages` | Get similar package list | - | ### Performance analysis tool | Tool | Description | Parameters | | --------------------------- | ------------------------------------- | ---------- | | `get_loader_time_all_files` | Get file loader time | - | | `get_loader_times` | Get compilation directory loader time | - | | `get_rule_info` | Get build rule scan results | - | ## Q\&A ### 1. Connection issues **Issue**: Unable to connect to Rsdoctor MCP Server or no data returned successfully **Solution**: - Ensure the Rsdoctor local Server has been successfully started. - Manually start the local Server, do not use MCP Client to start the project, as the local service of Rsdoctor will block the dialogue process of MCP Client. - If the Rsdoctor MCP server uses the `--port` parameter, please ensure the Rsdoctor startup port configuration is correct. - Check if the Rsdoctor plugin version meets the requirements. [Version requirements](/guide/usage/mcp.md#-version-requirements) --- url: /guide/usage/module-analysis.md --- # Module analysis ## Introduction **Rsdoctor** provides the `Module Reference Chain Analysis` module, which is mainly used to analyze the dependency tree of a specific Module, i.e., which modules depend on it, similar to [Webpack's stats.reasons](https://webpack.js.org/configuration/stats/#statsreasons). In this module, you can analyze the `Module` reference chain. If you have the need to split packages or want to see why a certain `Module` is being imported, you can quickly and clearly locate the reference chain through `Module Reference Chain Analysis`. ![](https://assets.rspack.rs/others/assets/rsdoctor/module-analysis-tree.png) ### This section's entry After clicking on an **Assets** in the `「Bundle Size」` page, the `「Module Tree」` will be displayed on the right side. Click on the **Module** to view the reference chain relationship diagram of that **Module**. ![](https://assets.rspack.rs/others/assets/rsdoctor/bailout-reason.gif) ### Glossary - **`Reasons`**: As the name suggests, it means the `[reason]` why a `Module` exists. Reasons indicate which `Module`s import this `Module`, and the entire `Reasons Tree` represents the upstream reference chain of this `Module`, including both direct and indirect parents. [Similar to Rspack's stats.reasons.](https://webpack.js.org/configuration/stats/#statsreasons) - **`Dependencies`**: The `Module`s that this `Module` depends on. - **`Bailout Reason`**: The reason why this `Module` failed Tree Shaking. ## Reasons dependency tree ### Introduction The `Reasons Tree` displays the dependency chain of this `Module`, showing which other `Modules` directly or indirectly import it. In this dependency tree, you can view the `Bundled Size` of the `Modules` along the dependency chain. You can also click the right arrow `>` to navigate to the `Module Reference Chain Analysis` page for that specific `Module`. - **Parent-child relationship in the dependency tree**: The parent node file is the one that is depended upon by the child node file and is therefore bundled into the output. Similarly, the grandchild node file is depended upon by the child node and is bundled into the output, and so on. ![](https://assets.rspack.rs/others/assets/rsdoctor/module-analysis-jump-icon.png) - The `Usage` tag displays the purpose of various module tags. - The `Concatenated` tag: - The `Concatenated` tag indicates that the module is a concatenated sub-module. Hover over it to see which main module it is aggregated into. This type of aggregated module cannot be further unpacked, so the specific `Bundled Size` cannot be determined, only the size of the entire concatenated module can be known. - Glossary: A **concatenated module** is when multiple modules are promoted or **concatenated into a closure** during packaging. For an explanation of `Concatenated Module`, refer to the [Glossary](/guide/usage/bundle-size.md#-glossary). - The `!` tag, hover over it to display the detailed path of the module. ![](https://assets.rspack.rs/others/assets/rsdoctor/module-analysis-icons.png) ## Bailout Reason ### Usage `Bailout Reason` shows the reason why this `Module` failed Tree Shaking. ![](https://assets.rspack.rs/others/assets/rsdoctor/bailout-reason.gif) You can also use MCP for analysis. By asking "Please help me to check why react-dom/client.js can not be tree-shaken?", the tool will help analyze why this module cannot be tree-shaken. ![tree-shaking](https://assets.rspack.rs/others/assets/rsdoctor/tree-shake-mcp.png) > For MCP analysis, see [MCP Analysis](/guide/usage/mcp.md) --- url: /guide/usage/plugins-analysis.md --- # Plugin analysis ## Overview In the **Rsdoctor** `Compile Analysis` secondary page `Plugins Analysis`, we can see the invocation data of all **Compiler Hooks** and **Compilation Hooks** used by the current Rspack or webpack project. The content is shown in the following figure: ![](https://assets.rspack.rs/others/assets/rsdoctor/plugins-analysis-overall.png) :::tip The plugin time will also calculate the internal plugin time of Rsdoctor. ::: ## Glossary The meanings of the fields in the data statistics table on the page are as follows: | Term | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------- | | Plugin Tap Name | Represents the name value when [.tap is called](https://github.com/webpack/tapable#hookhookmap-interface) | | Hook | Represents the **hook name** | | calls | Represents the **number of times called** | | duration(total) | Represents the **total time of all calls** | ## Usage instructions ### View bundler config If we need to view the Rspack or webpack configuration of the project, we can click on `View Bundler Config` in the upper right corner of the card. A floating layer will pop up, which contains the serialized **Bundler Config**, as shown in the following figure: ![](https://assets.rspack.rs/others/assets/rsdoctor/plugins-analysis-config.png) ## Reference documentation - [**Rspack Hooks**](https://www.rspack.rs/api/plugin-api.html#beforecompile) - [**Webpack Hooks**](https://webpack.js.org/api/compilation-hooks/) --- url: /guide/usage/project-overall.md --- # Project overall ## Overview In the main page of **Rsdoctor**, we can see a card named `Project Overall`, which provides information about the current project's **configuration, version, and alerts**. The content is shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/project-overall-1.jpg) ## Glossary | Term | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | errors | Represents the **error** level rules detected by Rsdoctor during the current run | | warns | Represents the **warn** level rules detected by Rsdoctor during the current run | | rspack | Represents the Rspack version obtained during the current run | | cwd | Represents the current working directory during the current run, i.e., [process.cwd()](https://nodejs.org/dist/latest-v22.x/docs/api/process.html#processcwd) | | cpu | Represents the CPU information | | memory | Represents the memory information during the current run | | node | Represents the version number of [Node.js](https://nodejs.org/) | | yarn | Represents the version number of [Yarn](https://yarnpkg.com/), displayed as `Not Found` if not found | | npm | Represents the version number of [npm](https://www.npmjs.com/) | | pnpm | Represents the version number of [pnpm](https://pnpm.io/), displayed as `Not Found` if not found | ## Usage ### View bundler config If we need to view the Rspack or webpack configuration of the project, we can click on `View Bundler Config` in the top right corner of the card. A popup window will appear, containing the serialized [Bundler Config](https://webpack.js.org/configuration/), as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/project-overall-config.jpg) ### errors / warns If the numbers displayed in the `errors` and `warns` sections of the card are greater than 0, we can click on them to view the corresponding details list. The following image shows an example using `warns`: ![](https://assets.rspack.rs/others/assets/rsdoctor/project-overall-warning.png) We can see the list of `warn` level alerts detected by Rsdoctor. --- url: /guide/usage/resolver.md --- # Resolver analysis :::tip - Resolve analysis capability is not currently supported in Rspack projects. - The Resolver analysis capability is disabled by default. To enable it, you can add `resolver` to the `features` array as shown in the example below. [features configuration](/config/options/options.md). ```js new rsdoctorWebpackPlugin({ features: [ 'resolver', // ...other features ], }); ``` ::: In the **Rsdoctor** `Module Resolve` section, we can see all the source files in the current Rspack project. By **clicking on a file**, we can view information such as the **module paths** imported in that file, the **before and after resolution path comparison**, and the **resolution time**, as shown in the following image: ![](https://assets.rspack.rs/others/assets/rsdoctor/resolver.png) ## Glossary The fields in the data statistics table on the page are defined as follows: | Term | Description | | ---------------------------- | --------------------------------------------------------------- | | Source Code | Represents the **source code** of the import statement | | Duration | Represents the **time taken** for resolution | | Resolve Result | Represents the **final path** after resolving the `Source Code` | --- url: /guide/usage/rule-config.md --- # Compilation diagnostic rules Building diagnostic rules is similar to `ESLint` like lint tools, but different from it in that `ESLint` performs code scanning and is unrelated to the build process. In contrast, the code diagnostics here are closely related to the build process of `Rspack or Webpack`, incorporating many internal parameters generated during the build process to aid judgment, such as ModuleGraph, Webpack's internal markings for each module, and runtime added after code transformation, among others. During the build process, if issues are discovered, they will be visible in the CLI and the final diagnostic summary webpage, as shown below: ![](https://assets.rspack.rs/others/assets/rsdoctor/rule-config-cli.png) ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-alerts.png) ## How to use Currently, Rsdoctor provides **built-in rules** and **custom rules**. ### Built-in Rules The existing diagnostic tool includes multiple rules, all of which are enabled by default. They are: 1. [\[E1001\] Duplicate Packages](/guide/rules/rules.md#e1001-duplicate-packages) 2. [\[E1002\] Cross Chunks Package](/guide/rules/rules.md#e1002-cross-chunks-package) 3. [\[E1003\] Loader Performance Optimization](/guide/rules/rules.md#e1003-loader-performance-optimization) 4. [\[E1004\] ECMA Version Check](/guide/rules/rules.md#e1004-ecma-version-check) 5. [\[E1005\] Default Import Check](/guide/rules/rules.md#e1005-default-import-check) For specific details, refer to [Built-in Rules](/guide/rules/rules.md). ### Custom rules Rsdoctor also collects analyzed data and allows users to integrate custom rules through the Linter API. For details on custom rules, refer to [Custom Rules](/guide/rules/rule-custom.md). --- url: /config/options/brief.md --- # brief :::warning Deprecated in V2, please use [output.mode: 'brief'](/config/options/output.md#mode) instead. Refer to [brief configuration migration](/config/options/options-v2.md#brief). ::: - **Type:** [BriefType](#brieftype) - **Optional:** `true` - **Default:** `undefined` Detailed configuration options for Brief mode are as follows: - **reportHtmlName:** Configures the filename of the HTML report in Brief mode. The default value is `report-rsdoctor.html`. - **writeDataJson:** (Deprecated, please use `output.options.type: ['json', 'html']`, refer to [output.options.type](/config/options/options-v2.md#options).) By default, Brief mode injects the analysis data directly into the HTML file, so no additional build analysis data files are generated. If you need to generate additional local JSON data files, you need to configure `writeDataJson: true`. ## briefType ```ts interface BriefConfig { reportHtmlName?: string | undefined; writeDataJson: boolean; } ``` - **Example:** ```js new RsdoctorRspackPlugin({ output: { mode: 'brief', }, }); ``` --- url: /config/options/disableClientServer.md --- # disableClientServer - **Type:** `boolean` - **Optional:** `true` - **Default:** `false`, when `process.CI` is true, the default value is true, meaning the report service is disabled by default in CI environments. :::tip It is recommended to set disableClientServer to true in CI environments, otherwise the started service will block the pipeline process. ::: Whether to automatically open the Rsdoctor report page. If you do not need to view the analysis report provided by Rsdoctor in the browser, you can enable this configuration item. --- url: /config/options/experiments.md --- # experiments Version: 1.0.0 ## enableNativePlugin - **Type:** `boolean` - **Optional:** `true` - **Default:** `true` By enabling the enableNativePlugin option, the Rspack native plugin moves the time-consuming data processing logic from Rsdoctor to the Rspack build stage, significantly improving build analysis efficiency and greatly reducing Rsdoctor's own analysis time. - **Example:** ```js new RsdoctorRspackPlugin({ experiments: { enableNativePlugin: true } }), ``` --- url: /config/options/features.md --- # features - **Type:** [RsdoctorWebpackPluginFeatures](#rsdoctorwebpackpluginfeatures) | [Array\](#rsdoctorwebpackpluginfeatures) | [RsdoctorRspackPluginFeatures](#rsdoctorrspackpluginfeatures) | [Array\](#rsdoctorrspackpluginfeatures) - **Optional:** `true` - **Default:** `['loader', 'plugins', 'bundle']` ## Configuration Description The `features` attribute is used for analysis feature toggles, and the specific functional items are as follows: - **loader**: Loader time consumption and code compilation change analysis, enabled by default. - **plugins**: Plugin calls and time consumption analysis, enabled by default. - **bundle**: Build artifact analysis, enabled by default. - **resolver**: Resolver analysis, disabled by default. - **lite**: **(lite mode will be deprecated in V2, refer to [lite mode deprecation notice](/config/options/options-v2.md#lite))** lite mode. The difference between lite mode and normal mode is that source code information is no longer displayed, only packaged code information is displayed, so the code analyzed on the page will also be packaged. Default is normal mode. Therefore, **the default configuration enables Bundle analysis capabilities, Loader and Plugin build-time analysis**. Resolver analysis capability is not enabled, and Rspack currently does not support Resolver analysis capabilities. ### Types - If you set `features` as an **array** type, the plugin will **only enable** the features you define in the `features` array. - If you set `features` as a **simple object** type, the plugin will **only disable** the features you set to `false` in the `features` object. ### Examples ```js new RsdoctorRspackPlugin({ // Only enable bundle, loader, plugins feature analysis, array form will override default configuration. features: ['bundle', 'loader', 'plugins'], }); ``` ```js new RsdoctorRspackPlugin({ features: { // Disable bundle analysis, other feature analysis remains default bundle: false, }, }); ``` ### Notes :::tip **If an "out of memory" error occurs, you can try the following:** 1. Enable **lite** mode. 2. Increase the node memory limit, for example: NODE\_OPTIONS=--max-old-space-size=8096. - Reason: Because during the build process, source code information is cached, which exceeds memory, so enabling `lite` mode can help alleviate this. - Difference: The difference between `lite` mode and normal mode is that source code information is no longer cached, only packaged code information is cached, so the code analyzed on the page will also be packaged. ::: ## RsdoctorWebpackPluginFeatures `features` type: ```ts interface RsdoctorWebpackPluginFeatures { /** * turn off it if you need not to analyze the executions of webpack loaders. * @default true */ loader?: boolean; /** * turn off it if you need not to analyze the executions of webpack plugins. * @default true */ plugins?: boolean; /** * turn off it if you need not to analyze the executions of resolver. * @default false */ resolver?: boolean; /** * turn off it if you need not to analyze the output bundle. * @default true */ bundle?: boolean; /** * turn on it if you just use lite mode. This mode do not have source codes. * @default false * @deprecated */ lite?: boolean; } ``` ## RsdoctorRspackPluginFeatures `features` type: ```ts interface RsdoctorRspackPluginFeatures { /** * turn off it if you need not to analyze the executions of webpack loaders. * @default true */ loader?: boolean; /** * turn off it if you need not to analyze the executions of webpack plugins. * @default true */ plugins?: boolean; /** * turn off it if you need not to analyze the output bundle. * @default true */ bundle?: boolean; /** * turn on it if you just use lite mode. This mode do not have source codes. * @default false * @deprecated */ lite?: boolean; } ``` --- url: /config/options/mode.md --- # mode :::warning - Deprecated in V2, please use [output.mode](/config/options/output.md#mode) instead. Refer to [mode configuration migration](/config/options/options-v2.md#mode). ::: - **Type:** `"normal" | "brief" | "lite"` - lite mode will be deprecated in V2, refer to [lite mode deprecation notice](/config/options/options-v2.md#lite) - **Optional:** `true` - **Default:** `normal` Select the Rsdoctor build report mode to use, which includes the following options: - **normal mode:** Generates a `.rsdoctor` folder in the build output directory, which contains various data files and displays code in the report page. The output directory can be configured via [reportDir](/config/options/options.md#reportdir). - **brief mode:** Generates an HTML report file in the `.rsdoctor` folder within the build output directory. All build analysis data will be consolidated and injected into this HTML file, which can be viewed by opening it in a browser. Brief mode also has additional configuration options, detailed at: [brief](/config/options/options.md#brief). - **lite mode:** Based on the normal mode, this mode does not display source code and product code, only showing the information of the bundled code. - lite mode will be deprecated in V2, refer to [lite mode deprecation notice](/config/options/options-v2.md#lite). --- url: /config/options/options-shared.md --- # ## Options **Type:** `Object` This is the options for the [RsdoctorWebpackPlugin](#rsdoctorwebpackplugin) and [RsdoctorRspackPlugin](#rsdoctorrspackplugin). It contains these properties: - [disableClientServer](#disableclientserver) - [features](#features) ### disableClientServer - **Type:** `boolean` - **Optional:** `true` - **Default:** `false` Whether to automatically open the Rsdoctor report page. If you do not need to view the analysis report provided by Rsdoctor in the browser, you can enable this configuration item. ### features - **Type:** [RsdoctorWebpackPluginFeatures](#rsdoctorwebpackpluginfeatures) | [Array\](#rsdoctorwebpackpluginfeatures) | [RsdoctorRspackPluginFeatures](#rsdoctorrspackpluginfeatures) | [Array\](#rsdoctorrspackpluginfeatures) - **Optional:** `true` - **Default:** `['loader', 'plugins', 'bundle']` #### features values The `features` attribute is used to analyze the function switches, and the specific functional items are as follows: - **loader**: Analysis of Loader time consumption and code compilation changes, enabled by default. - **plugins**: Analysis of Plugins calls and time consumption, enabled by default. - **bundle**: Analysis of build artifacts, enabled by default. - **resolver**: resolver analysis, disabled by default. - **lite**: \[**deprecated, please use [mode.lite](#mode)**] lite mode. The difference between lite mode and normal mode is that source code information is no longer cached, only packaged code information is cached, so the code analyzed on the page will also be packaged. The default is normal mode. Therefore, **the default configuration enables bundle analysis capabilities and Loader and Plugin build-time analysis**. The Resolver analysis capability is not enabled, and Rspack does not currently support Resolver analysis capabilities. :::tip **If an "out of memory" error occurs, you can try the following:** 1. Open the **lite** mode。 2. Increase the node memory limit, for example: NODE\_OPTIONS=--max-old-space-size=8096. - Reason: During the build process, source code information is cached, which exceeds memory. Therefore, enabling the **"lite" mode** can help alleviate the problem. - Difference: The difference between the "lite" mode and the normal mode is that source code information is no longer cached, only packaged code information is cached. Thus, the code analyzed on the page will also only be packaged. ::: #### features types - if the `features` is set as an `Array`, it will **open** the features which you define in this array **only**. - if the `features` is set as an `Object`, it will **close** the features which you set the value is `false`. #### RsdoctorWebpackPluginFeatures The types of `features` are as follows: ```ts interface RsdoctorWebpackPluginFeatures { /** * turn off it if you need not to analyze the executions of webpack loaders. * @default true */ loader?: boolean; /** * turn off it if you need not to analyze the executions of webpack plugins. * @default true */ plugins?: boolean; /** * turn off it if you need not to analyze the executions of resolver. * @default false */ resolver?: boolean; /** * turn off it if you need not to analyze the output bundle. * @default true */ bundle?: boolean; /** * turn on it if you just use lite mode. This mode do not have source codes. * @default false * @deprecated */ lite?: boolean; } ``` #### RsdoctorRspackPluginFeatures The types of `features` are as follows: ```ts interface RsdoctorRspackPluginFeatures { /** * turn off it if you need not to analyze the executions of webpack loaders. * @default true */ loader?: boolean; /** * turn off it if you need not to analyze the executions of webpack plugins. * @default true */ plugins?: boolean; /** * turn off it if you need not to analyze the output bundle. * @default true */ bundle?: boolean; /** * turn on it if you just use lite mode. This mode do not have source codes. * @default false * @deprecated */ lite?: boolean; } ``` --- url: /config/options/options-v2.md --- # Configuration Migration Guide **Rsdoctor introduced new configuration options in version 1.2.4**. These new configuration options are easier to configure, more extensible, and compatible with the upcoming v2.0 release. Configuration options from version 1.2.3 and earlier will still be supported, **but will be completely deprecated in Rsdoctor v2**, so we recommend migrating to the new configuration options in `1.2.4`. | Original Configuration | New Configuration | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | mode | Changed to configure `output.mode`. | | brief | Changed to configure `mode: 'brief'`, and configure `output.options` `type` as `html`. | | output.compressData | Changed to configure `mode: 'brief'`, and configure `output.options.type` as `json`. | | `mode: 'lite'` or `feature: 'lite'` | Changed to configure `mode: 'normal'`, and configure `output.options.reportCodeType` as `noCode` or `noAssetsAndModuleSource`. | | None | New `output.options.jsonOptions.section` configuration | ## Configuration Changes Details ### mode The `mode` in the original configuration is migrated to the nested `output.mode` for better integration with other output-related configurations. ### brief The current brief report mode outputs an HTML file as the report page. The new brief mode still supports JSON format, and for unified management of the same configuration, the brief configuration is moved to output.options. The original `brief` configuration is changed to configure `output.mode: 'brief'`, and configure `output.options` `type` as `html`. ### output.compressData The original `output.compressData` configuration is changed to configure `mode: 'brief'`, and configure `output.options.type` as `json`. ### lite The internal logic of lite mode is equivalent to `output.options.reportCodeType` being `noCode` or `noAssetsAndModuleSource`, mainly to solve the problem of large projects being too slow when opening reports or OOM during build. Considering that users cannot clearly distinguish the actual meaning of lite mode, having too many modes is not conducive to management and configuration, and the `output.options.reportCodeType` configuration is clearer, so `mode: 'lite'` will be deprecated in the future V2 version. The original `mode: 'lite'` and `feature: 'lite'` configurations are changed to configure `mode: 'normal'`, and configure `output.options.reportCodeType` as `noCode` or `noAssetsAndModuleSource`. ### output.options.jsonOptions.section Support for the new `output.options.jsonOptions.section` configuration for more granular JSON output option customization. For specific sections configuration items, refer to [output.options.jsonOptions.section](/config/options/output.md#jsonoptionssection). --- url: /config/options/options.md --- # Overview ## RsdoctorRspackPlugin The **RsdoctorRspackPlugin** class is exported by `@rsdoctor/rspack-plugin`, and the configuration options are [RsdoctorRspackPluginOptions](#rsdoctorrspackpluginoptions). **esm** ```ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; new RsdoctorRspackPlugin({ /** RsdoctorRspackPluginOptions */ }); ``` **cjs** ```js const { RsdoctorRspackPlugin } = require('@rsdoctor/rspack-plugin'); new RsdoctorRspackPlugin({ /** RsdoctorRspackPluginOptions */ }); ``` ## RsdoctorWebpackPlugin The **RsdoctorWebpackPlugin** class is exported by `@rsdoctor/webpack-plugin`, and the configuration options are [RsdoctorWebpackPluginOptions](#rsdoctorwebpackpluginoptions). **esm** ```ts import { RsdoctorWebpackPlugin } from '@rsdoctor/webpack-plugin'; new RsdoctorWebpackPlugin({ /** RsdoctorWebpackPluginOptions */ }); ``` **cjs** ```js const { RsdoctorWebpackPlugin } = require('@rsdoctor/webpack-plugin'); new RsdoctorWebpackPlugin({ /** RsdoctorWebpackPluginOptions */ }); ``` ## Options **Type:** `Object` This `Options` object is the configuration for [RsdoctorRspackPlugin](#rsdoctorrspackplugin) and [RsdoctorWebpackPlugin](#rsdoctorwebpackplugin) . It contains the following properties: - [disableClientServer](/config/options/disableClientServer.md) - **Client Service Control**: Whether to not automatically open the Rsdoctor report service after analysis is complete. - [experiments](/config/options/experiments.md) - **Experimental Features Configuration**: Enable experimental features for Rspack plugins, such as native plugin performance optimization. - [features](/config/options/features.md) - **Feature Toggle Configuration**: Control various analysis features of Rsdoctor, such as loader analysis, bundle analysis, rule checking, etc. - [output](/config/options/output.md) - **Output Related Configuration**: Control report output format, directory and other options, including mode, options, reportCodeType, etc. - [port](/config/options/port.md) - **Service Port Configuration**: Set the port number for the Rsdoctor development server, used for report preview during local development. - [supports](/config/options/supports.md) - **Feature Support Configuration**: Enable compatibility support for specific build tools, such as BannerPlugin, etc. - [brief](/config/options/brief.md) - **Brief Mode Configuration**: Control the generation of brief mode reports, including HTML filename and whether to generate JSON data files. - [mode](/config/options/mode.md) - **Build Report Data Output Mode**: Select the output mode for reports, supporting normal (normal mode) and brief (brief mode). ### RsdoctorRspackPluginOptions ```ts interface RsdoctorWebpackPluginOptions< Rules extends LinterType.ExtendRuleData[], > { /** Linter configuration */ linter?: LinterType.Options; /** Rsdoctor feature toggles */ features?: | Plugin.RsdoctorWebpackPluginFeatures | Array; /** * @deprecated Use `output.mode` instead. If using `lite` mode, please use `output.reportCodeType: 'noCode' or 'noAssetsAndModuleSource'` instead * Rsdoctor mode options: * - normal: Normal mode * - brief: Brief mode, only displays duration analysis and build artifact analysis results, does not display any code parts */ mode?: 'brief' | 'normal' | 'lite'; disableClientServer?: boolean; supports?: ISupport; port?: number; /** * @deprecated Use `output.options.htmlOptions` instead */ brief?: Config.BriefConfig; output?: Config.IOutput<'brief' | 'normal'>; experiments?: RsdoctorRspackPluginExperiments; } interface RsdoctorRspackPluginExperiments { /** * Whether to enable native plugin to improve performance * @default true */ enableNativePlugin?: boolean; } ``` ### RsdoctorWebpackPluginOptions RsdoctorWebpackPlugin is equivalent to `Omit` type. --- url: /config/options/output.md --- # output ## mode V1.2.4 Added - **Type:** `"normal" | "brief"` Rsdoctor report mode, default is `normal`. - **normal:** Generates a `.rsdoctor` folder in the build output directory, containing various data files and displaying code in the report page. The output directory can be configured via [reportDir](#reportdir). - **brief:** Generates an HTML report file in the `.rsdoctor` folder of the build output directory. All build analysis data is integrated and injected into this HTML file, which can be opened in a browser to view the report. Brief mode has more configuration options, see [brief](#brief) for details. :::tip Mode does not have a lite configuration option. The lite mode will be deprecated. Refer to [lite mode deprecation notice](/config/options/options-v2.md#lite-mode-deprecation-notice). ::: ## options V1.2.4 Added - **Type:** `BriefModeOptions | NormalModeOptions` - **Optional:** `true` - **Default:** `undefined` - **Description:** Based on different `mode` configurations, `options` supports different configuration items: ### mode: 'brief' Brief mode is used to generate lightweight analysis reports, supporting both HTML and JSON output formats. - **`type`**: Output type, supports `'html'` and `'json'` arrays, allowing multiple formats to be selected simultaneously - If configured with `['html', 'json']`, it will generate both an HTML file and a JSON file. - If configured with `['json']`, it will generate a JSON file named `rsdoctor-data.json`. - If configured with `['html']`, it will generate an HTML file. The filename can be configured via `htmlOptions.reportHtmlName`. - **`htmlOptions`**: HTML output related configuration - **`reportHtmlName`**: HTML report filename, defaults to `report-rsdoctor.html` - **`jsonOptions`**: JSON output related configuration - **`fileName`**: JSON stats filename, defaults to `rsdoctor-data.json` - **`sections`**: Module configuration for JSON output - **`moduleGraph`**: Whether to include module graph data, defaults to `true` - **`chunkGraph`**: Whether to include Chunk graph data, defaults to `true` - **`rules`**: Whether to include rules data, defaults to `true` **Notes:** - In Brief mode, the **`reportCodeType`** configuration item is invalid because only **`'noCode'`** is supported. **Configuration Example:** ```js new RsdoctorRspackPlugin({ output: { mode: 'brief', options: { // Output both HTML and JSON formats type: ['html', 'json'], htmlOptions: { reportHtmlName: 'my-report.html', }, }, }, }); ``` #### HTML vs JSON Output Format Differences | Feature | HTML Format | JSON Format | | --------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | | **File Structure** | Single file containing complete analysis report page | Pure data file requiring client support | | **Usage** | Can be opened directly in browser for viewing | Needs to be uploaded to Playground or parsed with client | | **Data Completeness** | Contains all analysis data and visualization interface | Contains only raw analysis data | | **File Size** | Larger (includes styles and scripts) | Smaller (data only) | | **Use Cases** | • Offline report viewing
• Direct sharing with others
• No secondary processing needed | • Upload to Playground
• Programmatic processing
• Data analysis and integration | | **Dependencies** | Self-contained, no external dependencies | Requires Rsdoctor client support | > For viewing analysis reports in Playground, see [Playground](/guide/start/playground.md). **Configuration Example Comparison:** ```js // Generate HTML report only (suitable for offline viewing) new RsdoctorRspackPlugin({ output: { mode: 'brief', options: { type: ['html'], htmlOptions: { reportHtmlName: 'build-report.html', }, }, }, }); // Generate JSON data only (suitable for uploading to Playground) new RsdoctorRspackPlugin({ output: { mode: 'brief', options: { type: ['json'], }, }, }); // Generate both formats (suitable for different use cases) new RsdoctorRspackPlugin({ output: { mode: 'brief', options: { type: ['html', 'json'], htmlOptions: { reportHtmlName: 'build-report.html', }, }, }, }); ``` ### mode: 'normal' In Normal mode, `options` is an empty object with no additional configuration items. ### Type Definitions #### BriefModeOptions ```ts interface BriefModeOptions { /** Output type, supports HTML and JSON */ type?: Array<'html' | 'json'>; /** HTML output related configuration */ htmlOptions?: BriefConfig; /** JSON output related configuration */ jsonOptions?: JsonOptions; } interface BriefConfig { /** HTML report filename, defaults to report-rsdoctor.html */ reportHtmlName?: string; /** Whether to additionally generate JSON data files, defaults to false */ writeDataJson: boolean; } interface JsonOptions { /** JSON stats filename, defaults to rsdoctor-data.json */ fileName?: string; /** Module configuration for JSON output */ sections?: JsonSectionOptions; } interface JsonSectionOptions { /** Whether to include module graph data, defaults to true */ moduleGraph?: boolean; /** Whether to include Chunk graph data, defaults to true */ chunkGraph?: boolean; /** Whether to include rules data, defaults to true */ rules?: boolean; } ``` #### NormalModeOptions NormalModeOptions currently has an empty Object type. ## reportCodeType - **Type:** `"noModuleSource" | "noAssetsAndModuleSource" | "noCode" | { noModuleSource?: boolean; noAssetsAndModuleSource?: boolean; noCode?: boolean }` - **In V2, only String type will be supported.** - **Optional:** `true` - **Default:** `undefined`, when undefined, outputs all complete data. - **Description:** Select the scope of output analysis data: - **Default**: Output all complete data - **`noModuleSource`**: Output data excluding module ([Module](https://rspack.rs/config/module#module)) code. Module code refers to the packaged module code of individual files within the Bundle. - **`noAssetsAndModuleSource`**: Output data excluding module ([Module](https://rspack.rs/config/module#module)) code and Assets product code - **`noCode`**: Output data excluding code, i.e., no code is output ### Output Data Comparison Table | Configuration | Included Data | Excluded Data | Use Cases | File Size | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------- | | **Default** (No Config) | **Complete build information:**
• Module graph data and its bundled code
• Assets code
• Other analysis data | None | • Development debugging
• Complete analysis | Largest | | **noModuleSource** | • Build information
• Module graph data and its bundled code
• Assets code
• Other analysis data | Module source code | • No need to view source code
• Memory leak issues | Medium | | **noAssetsAndModuleSource** | • Build information
• Module graph data and its bundled code
• Other analysis data | Module source code, Assets code | • Large projects
• No need to view source code and Assets code
• Memory leak issues | Smaller | | **noCode** | • Build information
• Module graph data
• Other analysis data | All code (Module source code + Module bundled code + Assets code) | • Large projects
• CI/CD
• Memory leak issues | Smallest | **Data output order from rich to simple:** `Default` > `noModuleSource` > `noAssetsAndModuleSource` > `noCode` > For the explanation of Asset and Module, see [Term](/config/options/term.md). - **Example:** ```js new RsdoctorRspackPlugin({ output: { reportCodeType: { noModuleSource: true } // { noAssetsAndModuleSource: true } } }), ``` ## reportDir - **Type:** `string` - **Optional:** `true` - **Default:** `undefined` The output directory for Rsdoctor reports. By default, it is the build output directory. ## compressData :::warning Deprecated in V2, please use `output.mode: 'brief'` and `output.options.type: 'json'` instead. Refer to [compressData configuration migration](/config/options/options-v2.md#compressdata). ::: - **Type:** `boolean` - **Optional:** `true` - **Default:** `true` compressData is used to configure whether to compress the analysis data under `[outputDir]/.rsdoctor`. --- url: /config/options/port.md --- # port - **Type:** `number` - **Optional:** `true` - **Default:** `random(3000, 8999)` Configure the port for the Rsdoctor server. --- url: /config/options/supports.md --- # supports - **Type:** [Supports Types](#supports-types) - **Optional:** `true` - **Default:** `undefined` This option is used to configure whether Rsdoctor enables support for certain detailed feature analysis capabilities, such as whether to enable compatibility with BannerPlugin. ## supportsTypes ```ts type ISupport = { banner?: boolean; parseBundle?: boolean; generateTileGraph?: boolean; }; ``` ## banner :::danger `supports.banner` option is only used for debugging, do not use it in production. ::: - **Type:** `boolean` - **Default:** `true` If `supports.banner` is enabled, Rsdoctor will enable compatibility logic for BannerPlugin. For more details, please refer to: [Supports BannerPlugin](/guide/usage/bundle-size.md#supports-bannerplugin) ## ~~generateTileGraph \[**Deprecated**]~~ Deprecated Rsdoctor supports generating Tree Map graphs by default, so this option does not need to be configured. ## parseBundle - **Type:** `boolean` - **Default:** `true` In some large repositories, the execution time of parsing the bundle is too long. Since the Parse Bundle analysis utilizes AST parsing and processing, it can be time-consuming when there are a large number of output files. If this capability is not necessary, it can be selectively disabled using the supports.parseBundle configuration. An example is shown below: ```ts chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { supports: { parseBundle: false, }, }, ]); ``` Disabling the Parse Bundle capability will only affect the visibility of the Bundled Size and Bundled Code of the modules in the bundle: ![](https://assets.rspack.rs/others/assets/rsdoctor/bundled-size.jpeg)![](https://assets.rspack.rs/others/assets/rsdoctor/bundled-code.png) --- url: /config/options/term.md --- # Terminology ## Common Terminology ### manifest.json When your project integrates with plugins provided by **Rsdoctor** (such as `@rsdoctor/webpack-plugin`, etc.), Rsdoctor will write **build-related data information** into a local JSON file: - The **filename is `manifest.json`** - The output **path is `project output directory/.rsdoctor/manifest.json`** ### Artifact Terminology Definitions ### assets (Resources | Artifact Files) **Definition:**\ Refers to all static files in the project, such as images, fonts, CSS, JS, SVG, etc. They are files that are output to the target directory after build and will eventually be loaded and used by the browser. **Examples:** - `logo.png`, `main.css`, `app.js` are all assets. ### chunk **Definition:**\ Rspack will package multiple modules (JS, CSS, etc.) into one or more files, and these files are bundles. A chunk may contain multiple Assets, for example: a chunk named index may contain two artifacts: index.js and index.css. ### module **Definition:**\ In Rspack, any file can be considered a module. The most common are JS modules (via `import` or `require`), but they can also be CSS, images, etc. Modules are the smallest units in the build process, and Rspack organizes them through a dependency graph. Assets are composed of collections of Modules. **Examples:** - Third-party files or source files, such as `index.js`, `button.js`, `style.css`, are all modules. These files are not artifact files, but they participate in the packaging process of artifact files and may eventually be packaged into artifact files. ### Summary Comparison | English Name | Role in Rspack | | ------------ | ---------------------------------------------------------- | | assets | Final artifacts, static files | | chunk | Output packaged files, a chunk may contain multiple assets | | module | Smallest unit in build, source files | --- url: /blog/release/release-note-0_1.md --- _January 24, 2024_ # Announcing Rsdoctor 0.1 ![Rsdoctor Banner](https://github.com/web-infra-dev/rsdoctor/assets/7237365/0f9d2e86-d919-451a-befa-fa84603a87cf) We are excited to announce the release of [Rsdoctor](https://rsdoctor.rs/) 0.1! Rsdoctor is a one-stop build analyzer for Rspack and Webpack. It allows for detailed analysis of the build process and bundles, making the build process more visual and transparent. ## 📌 Position **Rsdoctor** is a build analyzer for analyzing projects built with [Rspack](https://www.rspack.rs/) and [Webpack](https://webpack.js.org/). It supports analysis of projects such as [Rsbuild](https://rsbuild.rs/), [Create React App](https://create-react-app.dev/), [Modern.js](https://modernjs.dev/), and more. ![Position](https://assets.rspack.rs/others/assets/rsdoctor/rsdoctor-position.png) ## 🔥 Features - **Compilation Visualization**: Rsdoctor visualizes the compilation behavior and time consumption, making it easy to view build issues. - **Multiple Analysis Capabilities**: Rsdoctor supports build artifact, build-time analysis, and anti-degradation capabilities: - Build artifact support for resource lists and module dependencies, etc. - Build-time analysis supports Loader, Plugin, and Resolver building process analysis, including Rspack's builtin loaders. - Build rules support duplicate package detection and ES Version Check, etc. - Currently, bundle diff capabilities are also available. - **Support Custom Rules**: In addition to built-in build scan rules, Rsdoctor also supports users adding custom component scan rules based on the build data of Rsdoctor. - **Framework-Independent**: Rsdoctor support all projects built on Rspack or webpack. ## 🛠️ Introduction ### ⭐️ Overview - The overview page (i.e. the home page) can know **project configuration, diagnostic information, compilation information, and product status**. ![Overall](https://assets.rspack.rs/others/assets/rsdoctor/project-overall-1.jpg) - In addition to the project overview, we also provide diagnostic functions, including compilation diagnostics and duplicate packages diagnostics. If your compilation and products hit the diagnostic rules we defined, the corresponding warning alerts will appear on the tool's home page. **where you can see the detailed reference path of duplicate packages**: ![Overall-Alerts](https://assets.rspack.rs/others/assets/rsdoctor/overall-alerts.png) ### ⭐️ Compilation analysis Provides corresponding data and analysis functions for **Loaders, Plugins, and Module Resolve** to help you analyze problems in the compilation process. #### Loader analysis - This module mainly provides the function of data analysis such as input and output, estimated time consumption, and parameters within **Rspack or webpack Loaders**. ![](https://assets.rspack.rs/others/assets/rsdoctor/rsdoctor-loader-timeline.png)![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-all.png) #### Plugin analysis - This module mainly intercepts and collects data information such as the number of calls and estimated time consumption of Plugins. ![bundle](https://assets.rspack.rs/others/assets/rsdoctor/compile-plugin.jpg) #### Resolve analysis - This module mainly provides path data and estimated time consumption for module resolution in a single file within the project. Rspack does not currently support this module. ![bundle](https://assets.rspack.rs/others/assets/rsdoctor/resolver.png) ### ⭐️ Product analysis - In the **Bundle Size** page, we can see an overview of the product data information of the current project, as well as analyze the size and reasons for duplicate package imports. - In addition, we can also use the **Bundle Analysis** page to further analyze the relationship between the product and module in the current product, size data and other information, as well as the reasons for module introduction. ![bundle](https://assets.rspack.rs/others/assets/rsdoctor/bundle-size-overall.png) ## 📚 Quick start You can refer to the [Quick Start](https://rsdoctor.rs/guide/start/quick-start) to get started with **Rsdoctor**. ## 💡 Next steps **Improve Rsdoctor build analysis efficiency**: Currently, enabling Rsdoctor plugin increases project build time. In the next step, we will extract and convert some of Rsdoctor's build analysis logic into a rust plugin, built-in to [Rspack](https://www.rspack.rs/), in order to improve Rsdoctor's build analysis efficiency. ## Acknowledgements **Rsdoctor** has been inspired by outstanding projects in the community, and we would like to express our gratitude to them: - Refer to the analysis logic of artifact relationships from [bundle-stats](https://github.com/relative-ci/bundle-stats/tree/master/packages/cli#readme). - Refer to the module breakdown and analysis logic from [webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer). - [Statoscope](https://github.com/statoscope/statoscope/blob/master/README.md) is an excellent tool for analyzing build artifacts, and Rsdoctor is inspired by it in terms of build analysis. - [Webpack team and community](https://github.com/webpack/webpack/blob/main/README.md) have created an excellent bundling tool and a rich ecosystem. - [vite-plugin-inspect](https://github.com/antfu/vite-plugin-inspect) has inspired Rsdoctor's exploration of build process analysis. --- url: /blog/release/release-note-0_3.md --- _June 02, 2024_ # Announcing Rsdoctor 0.3 Rsdoctor 0.3 has been released! The new features of Rsdoctor 0.3 include: - Custom Extension Rules: Users can customize their own rule checks through the interface. - Support for Banner Plugin: Added support for the Banner Plugin, which adds template wrapping to the bundled code, allowing analysis of code changes. - Support for ESM Loader Analysis: Added support for analyzing ESM Loaders in the compilation analysis in Rspack. ## Custom extension rules Considering that users may have their own specific rule definition requirements, Rsdoctor provides an external interface for users to customize their own rule checks in addition to the internal rules already available. External extension interfaces need to be configured on the Rsdoctor plugin through the `extends` field, and their configurations are also placed in the `rules` field. For more details, please refer to: [Custom Extension Rules](/guide/rules/rule-custom.md) Additionally, the use of custom rules can also be applied for user data collection and reporting. [Data Reporting](/guide/rules/upload-data.md) - Example: ```ts // src/rules/assets-count-limit.ts import { defineRule } from '@rsdoctor/core/rules'; export const AssetsCountLimit = defineRule(() => ({ meta: { category: 'bundle', severity: 'Warn', title: 'assets-count-limit', defaultConfig: { limit: 10, }, }, check({ chunkGraph, report, ruleConfig }) { const assets = chunkGraph.getAssets(); if (assets.length > ruleConfig.limit) { report({ message: 'The count of assets is bigger than limit', detail: { type: 'link', link: 'https://rsdoctor.rs/zh/guide/start/quick-start', // This link just for show case. }, }); } }, })); ``` ```ts // rsbuild.config.ts import { AssetsCountLimit } from './rules/assets-count-limit'; export default { tools: { bundlerChain: (chain) => { chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { linter: { level: 'Error', extends: [AssetsCountLimit], rules: { 'assets-count-limit': [ 'on', { limit: 1, // rule custom configs }, ], }, }, }, ]); }, }, }; ``` ## Support for banner plugin Both Rspack and webpack support the BannerPlugin, which is an built-in plugin that allows you to add specific content at the top or bottom of the generated chunks. The added code will affect the parsing capability of the bundle. Therefore, Rsdoctor has added support for the Banner Plugin. Please refer to [Support for BannerPlugin](/guide/usage/bundle-size.md#support-for-bannerplugin) ## Support for ESM loader Starting from Rspack\@0.7.3, support for ESM Loader execution with `.js` extension and `type: module` configuration in `package.json` is added ([related issue](https://github.com/web-infra-dev/rspack/issues/5735)). Therefore, Rsdoctor also supports the analysis of ESM Loader, mainly supporting the following two types: 1. ESM Loader with `.mjs` extension. 2. ESM Loader with `.js` extension and `type: module` configuration in `package.json`. ### Support for defining port Support for [defining the port of Rsdoctor service](/config/options/options.md#port) has been added. - Example: ```ts chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { port: 8888, // port }, ]); ``` ## Support for parse bundle configuration In some large repositories, the execution time for parsing bundles is significant. This is because the Parse Bundle analysis relies on AST parsing and processing, which can be time-consuming when there are a large number of files. If this capability is not necessary, it can be selectively disabled using the `supports.parseBundle` configuration. Here is an example: ```ts chain.plugin('Rsdoctor').use(RsdoctorRspackPlugin, [ { supports: { parseBundle: false, }, }, ]); ``` Disabling the Parse Bundle capability only affects the ability to view the final bundled size and code of modules in the bundle (Bundled Code). ![](https://assets.rspack.rs/others/assets/rsdoctor/bundled-size.jpeg)![](https://assets.rspack.rs/others/assets/rsdoctor/bundled-code.png) --- url: /blog/release/release-note-0_4.md --- _October 09, 2024_ # Announcing Rsdoctor 0.4 Rsdoctor 0.4 is now released! The new features of Rsdoctor 0.4 include: - **Brief Mode**: Outputs a single HTML file, ideal for CI processes. - **Bundle Diff**: Compare and analyze changes between two build artifacts. - **Vue Loader Analysis**: Added support for loader analysis in Vue projects. ## Brief mode In Rsdoctor 0.4, a new **Brief mode** has been added, designed specifically for CI/CD scenarios. Brief mode consolidates the data report into a single HTML page, making it convenient for users to view historical build data in CI/CD and other scenarios. The main features of Brief mode are: - **Single report file**: Previously, Rsdoctor output multiple report data and `Manifest.json`, which was inconvenient for CDN upload and sharing. Brief mode outputs a single report, making it convenient for use in CI processes. - **Easy to configure**: Enable by configuring the [mode.brief](/config/options/options.md#mode) option in the Rsdoctor plugin. - **Report output**: The report will be generated in the build artifacts directory, and the output directory and filename of the Brief report can be configured. This feature greatly enhances the convenience of using Rsdoctor analysis reports in CI processes. The report can be uploaded to a CDN in the pipeline to display historical reports. [For more details, please refer to](/guide/start/cicd.md) ## Bundle diff Version: 0.4.5 The **Bundle Diff** feature helps users compare and analyze changes between two build artifacts. Key capabilities include: - **Total size change**: Displays the total size change between two build artifacts. - **File type change**: Compares the size changes of different types of files (JS, CSS, images, fonts, etc.). - **First screen resource change**: Analyzes the size changes of resources loaded on the first screen. - **Duplicate package count change**: Counts and compares the number of duplicate packages between two builds. - **NPM Packages change**: Displays changes in the number of NPM packages, including added, removed, and changed packages. - **Detailed data query**: Provides a detailed list module for deeper data query and analysis. - **Module-level comparison**: View the name, size, and change rate of modules, and supports viewing the code changes of modules. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-cards.png)![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-diff-module-list.png) This feature enhances the user's ability to visually analyze changes in build artifacts, helping users better understand and optimize build results. [For more details, please refer to](/guide/usage/bundle-diff.md) ### Next Plans to support Bundle Diff Action on GitHub to simplify degradation monitoring during the CI phase. ## Vue loader analysis Version: 0.4.5 Support for loader analysis for Vue projects has been added in Rsdoctor 0.4. ![](https://assets.rspack.rs/others/assets/rsdoctor/vue-loader.png) ## Other features - **Rspack's builtin:lightningcss-loader analysis**: Added support for [builtin:lightningcss-loader](https://rspack.rs/guide/features/builtin-lightningcss-loader#builtin-lightningcss-loader) analysis. - **Performance optimization**: - Reduced the size of the `@rsdoctor/client` package by 60%, improving page rendering speed. - Reduced third-party dependencies, thereby reducing the total download size during installation. --- url: /blog/release/release-note-1_0.md --- _March 19, 2025_ # Announcing Rsdoctor 1.0 We are excited to announce the official release of **Rsdoctor 1.0**! After a year of development and testing, we are proud to introduce **Rsdoctor 1.0** — a build analyzer tailored for the [Rspack](https://rspack.rs/) ecosystem and fully compatible with the [webpack](https://webpack.js.org/) ecosystem. Rsdoctor is committed to being a one-stop, intelligent build analyzer that makes the build process transparent, predictable, and optimizable through visualization and smart analysis, helping development teams precisely identify bottlenecks, optimize performance, and improve engineering quality. ## Why Rsdoctor In the field of build analysis, the community already has some mature tools, such as [webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer) for visualizing bundles, and [Statoscope](https://github.com/statoscope/statoscope/) for comprehensive resource analysis. In addition, [speed-measure-webpack-plugin](https://github.com/stephencookdev/speed-measure-webpack-plugin) can be used to analyze the execution time of plugins and loaders, and locate build performance bottlenecks. However, these tools still have some shortcomings, such as lack of detailed display of build details, lack of comprehensive build problem analysis capabilities, incompatibility with Rspack, and lack of build warning scanning capabilities. In summary, community tools have the following areas for improvement: 1. **Lack of detail**: Traditional tools cannot delve into the details and changes of the build process, and to view the compilation details of a loader, developers often need to set breakpoints for step-by-step debugging. 2. **Functional limitations**: Current analyser typically only display bundle data, lacking build scanning capabilities, unable to proactively provide optimization suggestions, and do not support custom scanning rules. 3. **Support for Rspack**: Existing tools do not fully support Rspack, for example, they cannot analyze Rspack's [builtin loader](https://rspack.rs/guide/features/builtin-swc-loader) of Rspack. ### Birth of Rsdoctor Based on the above situation, we decided to develop a build analyzer focused on the Rspack ecosystem — **Rsdoctor**. We designed an intuitive user interface for Rsdoctor, and Rsdoctor extends the **loader profiling capability** by combining the advantages of multiple tools to more deeply analyze the loader behavior in the compilation phase, **built-in the scanning and detection rules for artifacts and compilation**, and supports user **custom rules**. Rsdoctor not only supports Rspack and webpack, but also supports all tools and frameworks based on Rspack or webpack, such as: [Docusaurus](https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-rsdoctor), [Rspeedy (Lynx)](https://lynxjs.org/rspeedy/), [Storybook](https://github.com/rstackjs/storybook-rsbuild), [Next.js](https://nextjs.org/), [Nuxt](https://nuxt.com/), [Re.Pack](https://re-pack.dev/), [Modern.js](https://modernjs.dev/), [Rsbuild](https://rsbuild.rs/), [Rspress](https://rspress.rs/) and [Rslib](https://rslib.rs/). Rsdoctor can be used to: - **As a build analyzer**: Help developers understand every aspect of the build process, and provide detailed compilation and bundle analysis. - **As an extensible analysis tool**: Allow developers to customize analysis rules according to project requirements, and achieve targeted optimization of the build process. ## Who is using Rsdoctor has been widely used within ByteDance, helping developers efficiently analyze and solve various problems in the build process. Since its open source in 2024, Rsdoctor's npm weekly downloads has exceeded **100k**. In the community, Rsdoctor has been integrated into frameworks such as [Docusaurus](https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-rsdoctor) and [Lynx](https://lynxjs.org/rspeedy/use-rsdoctor.html). In addition, Rsdoctor has also been adopted by large projects such as [Sentry](https://github.com/getsentry/sentry/pull/63865), [NocoBase](https://github.com/nocobase/nocobase/blob/main/packages/core/build/src/buildPlugin.ts#L493) and [Grafana](https://github.com/grafana/grafana/pull/94729). In the future, Rsdoctor will continue to provide first-class support for all tools in the **Rstack** (`Rspack stack` abbreviation) ecosystem: ![](https://assets.rspack.rs/rstack/rstack-overview.png) ## Typical use cases Rsdoctor offers a rich set of features, detailed content can be found in the [Feature Navigation](/guide/start/features.md). Here are some typical use cases that demonstrate how Rsdoctor effectively solves common build problems: ### 1. "Why is the build speed too slow?" During the build process, if you find that the compilation speed is too slow, you can use the [Loader Timeline](/guide/usage/loaders-timeline.md) to view the time consumption of loader execution, and understand the compilation time consumption of each file by each loader. This way, you can find loaders with excessive time consumption. ![](https://assets.rspack.rs/rsdoctor/assets/loader-timeline-overall-v1-0.png) ### 2. "Outputs are not as expected?" During the build, there may be problems where the outputs do not match expectations, such as runtime exceptions or style errors. The [Loader Details](/guide/usage/loaders-analysis.md) page of Rsdoctor can help you examine the changes made by the loader to a specific file before and after compilation. ![](https://assets.rspack.rs/rsdoctor/assets/babel-import-errors-v1-0.png) ### 3. "How to split the chunks reasonably?" We can use the [Bundle Analysis](/guide/usage/bundle-size.md) page to look at the modules tree of a particular artifact to see what modules the chunk contains, and then use the [splitChunks](https://rspack.rs/zh/plugins/webpack/split-chunks-plugin) configuration of Rspack to split the chunks appropriately. ![](https://assets.rspack.rs/rsdoctor/assets/bundle-size-overall-v1-0.png) ### 4. "How to analyze the reasons for the increase in bundle size?" When a certain version is launched, if the performance of the online page deteriorates due to the increase in the size of the artifact, you can use the [Bundle Diff](/guide/usage/bundle-diff.md) feature of Rsdoctor to compare the details of the bundles of two commits, as well as the changes in the npm packages they depend on. ![](https://assets.rspack.rs/rsdoctor/assets/bundle-diff-assets-v1-0.png) ### 5. "Why is a certain module bundled?" During the build process, if you want to know why a certain module file is bundled into the artifact, you can click on the `Module Graph` icon behind the module in the Modules tree on the [Artifact Analysis](/guide/usage/bundle-size.md) page to view the upstream dependency relationship of the module. ![](https://assets.rspack.rs/rsdoctor/assets/module-analysis-tree-v1-0.png) ## What's new in 1.0 ### 🎨 Brand new UI In version 1.0, we have comprehensively optimized the user interface of Rsdoctor, making it more clear, elegant, and easy to navigate. The new design is dedicated to improving the user experience, making information display more intuitive and efficient. ### 🚀 Faster analysis In large projects, enabling Rsdoctor can increase the overall build time. To solve this problem, we rewrote the time-consuming data processing logic in Rsdoctor in Rust, and integrated it into Rspack. This optimization effectively improves the build analysis performance of Rsdoctor, and reduces the overall analysis time by more than **20%**. In the future, we will continue to native more modules to further improve the analysis efficiency. This optimization can be enabled through the [enableNativePlugin](/config/options/options.md#enablenativeplugin) option: ```ts new RsdoctorRspackPlugin({ experiments: { enableNativePlugin: true, }, }); ``` ### 🔍 Module searching - **Search Module Capability**: In the `Bundle Size` page, we have added a module search function. Users can quickly locate and view the `Assets` where the module is located by entering the module name, making it more convenient to analyze the reference relationship and size of the module. [Details](/guide/usage/bundle-size.md#%E6%A8%A1%E5%9D%97%E6%90%9C%E7%B4%A2%E5%8A%9F%E8%83%BD) ![](https://assets.rspack.rs/rsdoctor/assets/search-modules-v1-0.png) ### 🛠️ New scanning rules - [Duplicate package detection](/guide/rules/rules.md#e1002-cross-chunks-package): Added a rule for detecting duplicate packages across chunks, which can scan for duplicate packages in different `chunks`. These duplicate packages may cause redundant code in the build. - [ECMA version checking](/guide/rules/rules.md#e1004-ecma-version-check): Enhanced the ECMA version detection rule, used to detect incompatible advanced syntax. ```ts new RsdoctorRspackPlugin({ linter: { rules: { 'ecma-version-check': [ 'Warn', { ecmaVersion: 2015, }, ], }, }, }); ``` ## How to use 1.0 - If you are using any tool or framework based on Rspack or webpack, you can refer to the [Quick Start](/guide/start/quick-start.md) to start using Rsdoctor. - If you are using Rsdoctor 0.4 or earlier, please note that 1.0 contains a few incompatible updates: - The `reportCodeType` and `reportDir` configuration items in the plugin configuration have been moved to [output](/config/options/options.md#reportcodetype). > Welcome to give a star 🌟 to the [Rsdoctor GitHub](https://github.com/web-infra-dev/rsdoctor) repository. ## Next steps - **AI powered analysis**: The build analysis data collected by Rsdoctor is very rich, but there may be a certain learning curve for new users. Therefore, we will integrate AI capabilities into Rsdoctor to help users quickly extract key information from massive data, provide intelligent optimization suggestions, and reduce the threshold of build analysis. - **CI proactive monitoring**: Rsdoctor will extend its capabilities in CI environments by introducing [Rsdoctor CI Action](https://github.com/web-infra-dev/rsdoctor/discussions/491), based on the existing [Bundle Diff](/guide/usage/bundle-diff.md) feature. This will provide automated monitoring of bundle sizes and alerts for performance issues to ensure quality. - **Further Native**: Due to the implementation of Rspack in Rust and the use of a multi-threaded architecture, the current analysis of the built-in loader of Rspack by Rsdoctor is not accurate enough. We plan to optimize the analysis mechanism based on [Rspack Native Plugin](/config/options/options.md#enablenativeplugin), and provide more accurate loader performance data and compilation behavior insights. **Finally, thank you to all the developers who have contributed to Rsdoctor ❤️**: [@9aoy](https://github.com/9aoy)、[@bin1357](https://github.com/bin1357)、[@cairon666](https://github.com/cairon666)、[@cclap2020](https://github.com/cclap2020)、[@charpeni](https://github.com/charpeni)、[@chenjiahan](https://github.com/chenjiahan)、[@ChuHoMan](https://github.com/ChuHoMan)、[@cnryb](https://github.com/cnryb)、[@Gehbt](https://github.com/Gehbt)、[@gezhicui](https://github.com/gezhicui)、[@HigherOrderLogic](https://github.com/HigherOrderLogic)、[@iamleniac](https://github.com/iamleniac)、[@inottn](https://github.com/inottn)、[@jkzing](https://github.com/jkzing)、[@KyrieLii](https://github.com/KyrieLii)、[@kwonoj](https://github.com/kwonoj)、[@LingyuCoder](https://github.com/LingyuCoder)、[@nanianlisao](https://github.com/nanianlisao)、[@nhducit](https://github.com/nhducit)、[@NickBolles](https://github.com/NickBolles)、[@nyqykk](https://github.com/nyqykk)、[@puppet-666](https://github.com/puppet-666)、[@SoonIter](https://github.com/SoonIter)、[@sudhakar-s](https://github.com/sudhakar-s)、[@Timeless0911](https://github.com/Timeless0911)、[@tinywaves](https://github.com/tinywaves)、[@trueLoving](https://github.com/trueLoving)、[@wChenonly](https://github.com/wChenonly)、[@zllkjc](https://github.com/zllkjc)。 --- url: /blog/release/release-note-1_2.md --- _August 2025_ # Announcing Rsdoctor 1.2 Rsdoctor 1.2 has been released! 🎉 - **Deep concatenated module analysis**: Added the ability to analyze the size of concatenated modules, helping developers more accurately identify the actual build size after Tree Shaking. - **Bundle Size Analysis with Gzip Support**: Bundle size analysis now displays the size after gzip compression, making it easier for developers to understand the real size of production assets. - **Enhanced Treemap Visualization**: Introduced and improved the Treemap (rectangle tree map) feature, allowing developers to gain more intuitive insights into bundle composition and resource distribution. - **Rsdoctor MCP**: Rsdoctor MCP is an LLM-powered build analysis tool that helps developers quickly obtain build analysis results through Q\&A interactions. ## Deep concatenated module analysis During the Rspack build process, certain modules are hoisted or aggregated into a single closure, forming a concatenated module to improve browser execution efficiency and reduce artifact size. Previously, Rsdoctor could not further decompose and analyze the internal structure of these concatenated modules, as they cannot be further split through AST parsing. **Rsdoctor 1.2** supports the ability to analyze concatenated module sizes, helping developers accurately understand the actual build size of sub-modules (aggregated modules) after **tree shaking and compression**, facilitating analysis of how concatenated modules affect final bundle size and optimization of code splitting strategies. Additionally, **the Rsdoctor plugin built into Rspack (>=1.4.11)** has enhanced source map capabilities, allowing seamless analysis of concatenated modules **without enabling source maps**. **However, Webpack projects still require source maps to be enabled.** > [View usage details](/guide/usage/bundle-size.md#support-for-concatenated-module-analysis) ## Enhanced treemap visualization Previously, Rsdoctor's Treemap view was implemented based on webpack-bundle-analyzer, which required Rsdoctor to go through webpack-bundle-analyzer's processing pipeline again after completing its analysis, reducing overall analysis efficiency. Additionally, Treemap page loading was slow, while Treemap is precisely the most commonly used visualization view for developers when analyzing bundles. **Rsdoctor 1.2** introduces a new classic Treemap artifact analysis view, helping developers more intuitively visualize and analyze bundle composition, Assets, and Modules proportions. You can also search for module resources, click on the module resource, and zoom in to the module area. > [View usage details](/guide/usage/bundle-size.md#bundle-treemap-graph) ![](https://assets.rspack.rs/others/assets/rsdoctor/treemap.gif) ## Support gzip size To more accurately reflect production environment size performance, Rsdoctor has added support for analyzing gzip compressed sizes, which can be viewed on the Bundle Size page and TreeMap page, as shown below: ![](https://assets.rspack.rs/others/assets/rsdoctor/treemap-gzip.png) This shows a comparison between original size and gzip compressed size, providing more accurate reference data for production environment optimization. ## Rsdoctor MCP Rsdoctor provides rich build analysis data, but developers need to spend time on page interactions and learning costs to perform build analysis and optimization. Therefore, we hope to leverage LLM for more intelligent build analysis to help users obtain analysis results more quickly. Rsdoctor v1.1 introduced MCP support, which is based on **Model Context Protocol (MCP)** protocol, combining Rsdoctor's analysis capabilities with LLM's intelligent understanding abilities. Through natural language Q\&A interactions, developers can quickly obtain build analysis results without needing to deeply understand complex analysis interfaces and data structures. Its main features include obtaining artifact information, dependency analysis, optimization suggestions, compilation performance, and tree shaking analysis among other core analytical capabilities. Rsdoctor MCP supports natural language Q\&A - you can directly ask questions like "Which packages have the largest volume?" or "Why wasn't this module tree-shaken?" The system will intelligently analyze and provide optimization suggestions, helping you quickly identify and resolve build issues. > [View usage details](/guide/usage/mcp.md) *** In addition, the 1.1-1.2 versions also included other capability changes. For complete update details, please refer to: [Release page](https://github.com/web-infra-dev/rsdoctor/releases) --- url: /blog/topic/duplicate-pkg-problem.md --- # Duplicate dependency problem Rsdoctor will report cases where multiple duplicate dependencies exist in the same bundler's artifact. ![](https://assets.rspack.rs/others/assets/rsdoctor/bundle-alerts.png) ## Hazards of duplicate packages - **Security** - Many packages adopt singleton mode and are only loaded once by default. Examples include core-js, react, and some component libraries. Having multiple versions coexist can cause runtime errors. - **Runtime Performance** - Increases artifact size, slowing down network transmission - Same code for the same functionality runs multiple times ## How to solve duplicate package Problems? To solve the issue of multiple versions of dependencies, you can address it from both the dependency and build aspects. ### Dependency aspect #### 1. Use the npm dedupe command Generally, package managers try to install the same version of a package based on the semver range. However, long-term projects may have some duplicate dependencies due to the existence of lock files. Package managers provide the `dedupe` command, such as `npm/yarn/pnpm dedupe`, to optimize duplicate dependencies within the correct semver range. #### 2. Use resolutions Under the constraints of semver, the effectiveness of the dedupe command may not be ideal. For example, if the artifact contains dependencies `debug@4.3.4` and `debug@3.0.0`, where they are respectively depended on by `"debug": "^4"` and another package's `"debug": "^3"`. In this case, you can try using the `resolutions` feature of the package manager, such as pnpm's [**pnpm.overrides**](https://pnpm.io/package_json#pnpmoverrides), [**.pnpmfile.cjs**](https://pnpm.io/pnpmfile#hooksreadpackagepkg-context-pkg--promisepkg), or **yarn's resolutions**. The advantage of these features is that they can break free from the constraints of semver and change the version declared in `package.json` during installation to precisely control the installed version. However, before using them, it is important to consider the compatibility between package versions and evaluate whether optimization is necessary. For example, whether the logic changes between different versions of the same package will affect the functionality of the project. ### Build aspect #### Use [resolve.alias](https://www.rspack.rs/config/resolve.html#resolvealias) Almost all bundlers support customizing the resolution paths for npm packages. Therefore, we can eliminate duplicate dependencies by manually specifying the resolve paths for packages during compilation. For example, using **Rspack** or **Webpack**, if `lodash` is duplicated in the build, we can configure it as follows to specify the resolve paths for all `lodash` packages to the `node_modules` directory in the current directory. ```js title="rspack.config.js" const path = require('path'); module.exports = { //... resolve: { alias: { lodash: path.resolve(__dirname, 'node_modules/lodash'), }, }, }; ``` This method also requires attention to the compatibility between package versions. ## Cases of handling duplicate packages ### Duplicate packages in pnpm-workspace In this project, the `web` app depends on `react@18.2.0` and imports `component` using `"component": "workspace:*"`. The `component` package, in turn, depends on `react@18.1.0`. The project structure is as follows: ```txt ├── node_modules ├── apps │ └── web │ ├── node_modules │ │ ├── component -> ../../packages/component │ │ └── react -> ../../../node_modules/.pnpm/react@18.2.0 │ ├── src │ │ └── index.js │ ├── rspack.config.js │ └── package.json └── packages └── component ├── node_modules │ └── react -> ../../../node_modules/.pnpm/react@18.1.0 ├── src │ └── index.js └── package.json ``` When executing `rspack build` under `apps/web`, the code in the `web` directory will be resolved to `react@18.2.0`, and then the code in the `component` directory will be resolved to `react@18.1.0`. This results in the output of the web project containing two versions of `React`. #### Solution This issue can be resolved using the `resolve.alias` configuration of the bundler, such as Rspack or webpack. By specifying the resolve path for `React` to only resolve to `apps/web/node_modules/react`, you can ensure that only one version of `React` is included in the output. Here is an example code: ```javascript // apps/web/rspack.config.js const path = require('path'); module.exports = { //... resolve: { alias: { react: path.dirname(require.resolve('react/package.json')), }, }, }; ``` #### Duplicate packages caused by peer dependency This handling method also applies to projects with duplicate packages caused by multiple instances of **[peerDependencies](https://pnpm.io/how-peers-are-resolved)** in `pnpm workspace`. The project directory structure is as follows: ```txt ├── node_modules ├── apps │ └── web │ ├── node_modules │ │ ├── component -> ../../packages/component │ │ ├── axios -> ../../../node_modules/.pnpm/axios@0.27.2_debug@4.3.4 │ │ └── debug -> ../../../node_modules/.pnpm/debug@4.3.4 │ ├── src │ │ └── index.js │ ├── rspack.config.js │ └── package.json └── packages └── component ├── node_modules │ └── axios -> ../../../node_modules/.pnpm/axios@0.27.2 ├── src │ └── index.js └── package.json ``` In this project, when executing `rspack build` under `apps/web`, the code in the `web` directory will be resolved to `axios@0.27.2_debug@4.3.4`, and then the code in the `packages/component` directory will be resolved to `axios@0.27.2`. Although they are the same version, they have different paths, resulting in two copies of `axios` in the output. The solution is to configure the `web` project to only resolve the `axios` package under the `web` directory's `node_modules`. ```javascript // apps/web/rspack.config.js alias: { 'axios': path.resolve(__dirname, 'node_modules/axios') } ``` --- url: /blog/topic/loader-optimization.md --- # Loader analysis and optimization Optimizing loaders is a common way to improve the performance of Rspack or webpack compilation. In most cases, besides replacing the loader with a faster one, we can also reduce execution by setting [module.rule.exclude](https://webpack.js.org/configuration/module/#ruleexclude) for the loader. Rsdoctor provides two core modules, [Loader Overall](/guide/usage/loaders-timeline.md) and [Loader Analysis](/guide/usage/loaders-analysis.md), to help you optimize based on the loader's invocation information. ## How to analyze? Regardless of the optimization method used for loaders, we need to obtain data information about the loaders, such as **which files a loader compiles** and **time-consuming information for compiling certain files**, in order to optimize more accurately. ### File tree structure With the Loader Analysis module provided by Rsdoctor, we can see **a tree structure composed of all files that pass through the loaders during the entire compilation process**, as shown in the following figure: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-all.png) ### Analyzing directories By **clicking on a directory**, you can see the **time-consuming statistics of all loaders** under the currently **selected directory** on the right side of the file tree, such as the number of files processed by a loader and **the estimated time** consumption. The content of the "Statistics of \*\*\*" card is shown in the following figure: ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-table.png) We can intuitively know **the time-consuming data of this folder**, such as the number of files processed by a certain loader and the estimated time consumption, as well as the sum of all data, which further helps us make decisions on how to optimize the loader. :::tip Optimization Tips Usually, in the directories of third-party libraries inside **`node_modules`**, we can easily determine whether it is necessary to set [module.rule.exclude](https://webpack.js.org/configuration/module/#ruleexclude) for this directory based on the time-consuming information of the loader, in order to reduce the execution of loaders with long execution time, such as the common `babel-loader`. ::: ### Analyzing files By **clicking on a file**, a mask layer will pop up, showing a list of all loaders that have been executed on the currently clicked file. By **clicking on a loader**, you can see the **input**, **output**, and **parameter data information of the target loader** when it is called. ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-code-change.png) - Parameter Data Information: Click on "**show more**" or the expand button in the upper left corner to view the corresponding parameter information. ![](https://assets.rspack.rs/others/assets/rsdoctor/loader-analysis-options.png) We can use the loader information of individual files here to troubleshoot issues and decide whether to add them to [module.rule.exclude](https://webpack.js.org/configuration/module/#ruleexclude). :::tip Optimization Tips Usually, for internal packages inside the project (i.e., outside the cwd, usually the workspace), we can determine whether it is necessary to set [module.rule.exclude](https://webpack.js.org/configuration/module/#ruleexclude) for this directory based on **the loader time-consuming information** of the directory and **the input-output information** of individual files (because these internal packages may already have good compatibility with ES syntax). ::: ## Learn more You may want to learn more about the usage of the Loader Analysis module: [Loader Timeline Usage Learn how to use the Loader Timeline in Rsdoctor ](/guide/usage/loaders-timeline)[Loader Analysis Usage Learn how to operate and use the Loader Analysis in Rsdoctor ](/guide/usage/loaders-analysis) --- url: /index.md --- body:not(.notTopArrived) .rp-nav {background: transparent !important; border-bottom: none !important;}.rp-nav {background: color-mix(in srgb,var(--rp-c-bg) 60%,transparent);backdrop-filter: blur(25px);-webkit-backdrop-filter: blur(25px);}![background](https://assets.rspack.rs/rspack/assets/landingpage-background-compressed.png)![logo](https://assets.rspack.rs/rsdoctor/rsdoctor-logo-960x960.png)# Rsdoctor Analyzer for Rspack & webpack Visualize the building process Quick Start[GitHubGitHub](https://github.com/web-infra-dev/rsdoctor)🛠️## Unlimited Framework Rsdoctor support all projects built on Rspack or webpack. 🚀## Compile's Time To display the compile execution time and process in the form of a timing diagram. 🦄## Compile's Actions Visually view the compilation changes of each file in each loader. 🎯## Bundle Analysis Visually view the bundles & modules relationship, module reference relationship and repeated packages in detail. 🎨## Bundle Diff Through comparison, the deterioration and change of the product are found. 🔍## Build Scan Built-in build rule scanning, and also supports custom rules. # Rstack A unified JavaScript toolchain centered on Rspack, with high performance and consistent architecture [![Rspack](https://assets.rspack.rs/rspack/rspack-logo.svg)RspackA high performance JavaScript bundler written in Rust, with webpack-compatible API rspack.rs](https://rspack.rs)[![Rsbuild](https://assets.rspack.rs/rsbuild/rsbuild-logo.svg)RsbuildAn Rspack-based build tool that provides out-of-the-box setup rsbuild.rs](https://rsbuild.rs)[![Rslib](https://assets.rspack.rs/rslib/rslib-logo.svg)RslibA Rsbuild-based library development tool for creating libraries and UI components rslib.rs](https://rslib.rs)[![Rspress](https://assets.rspack.rs/rspress/rspress-logo-480x480.png)RspressAn Rsbuild-based static site generator for creating documentation sites rspress.rs](https://rspress.rs)[![Rsdoctor](https://assets.rspack.rs/rsdoctor/rsdoctor-logo-480x480.png)RsdoctorA one-stop build analyzer that makes the build process transparent rsdoctor.rs](https://rsdoctor.rs)[![Rstest](https://assets.rspack.rs/rstest/rstest-logo.svg)RstestA testing framework that provides first-class support for Rspack ecosystem rstest.rs](https://rstest.rs/)[![Rslint](https://assets.rspack.rs/rslint/rslint-logo.svg)RslintA high-performance JavaScript and TypeScript linter based on typescript-go rslint.rs](https://rslint.rs/)Rsdoctor is free and open source software released under the MIT license. © 2024-present ByteDance Inc.