diff --git a/packages/plugin-react/README.md b/packages/plugin-react/README.md index af7a2d54..e668f02a 100644 --- a/packages/plugin-react/README.md +++ b/packages/plugin-react/README.md @@ -36,7 +36,19 @@ export default defineConfig({ }) ``` -> `node_modules` are never processed by this plugin (but esbuild will) +> [!NOTE] +> `node_modules` are not processed by this plugin by default (unlike esbuild), regardless of the `include` option. If you want to include them, you can set the `excludeNodeModules` option to `false`. + +### excludeNodeModules + +By default, the plugin excludes `node_modules` from being processed. If you want to include them, you can set this option to `false`: + +```js +react({ excludeNodeModules: false }) +``` + +> [!NOTE] +> Including `node_modules` can slow down the development server, so use this option with caution. ### jsxImportSource diff --git a/packages/plugin-react/src/index.ts b/packages/plugin-react/src/index.ts index 8103e2f2..0c819d17 100644 --- a/packages/plugin-react/src/index.ts +++ b/packages/plugin-react/src/index.ts @@ -37,6 +37,13 @@ async function loadBabel() { export interface Options { include?: string | RegExp | Array exclude?: string | RegExp | Array + + /** + * Whether to exclude `node_modules` from being processed. + * @default true + */ + excludeNodeModules?: boolean + /** * Control where the JSX factory is imported from. * https://esbuild.github.io/api/#jsx-import-source @@ -113,6 +120,7 @@ const tsRE = /\.tsx?$/ export default function viteReact(opts: Options = {}): PluginOption[] { const include = opts.include ?? defaultIncludeRE const exclude = opts.exclude + const excludeNodeModules = opts.excludeNodeModules ?? true const filter = createFilter(include, exclude) const jsxImportSource = opts.jsxImportSource ?? 'react' @@ -225,12 +233,12 @@ export default function viteReact(opts: Options = {}): PluginOption[] { ...(exclude ? makeIdFiltersToMatchWithQuery(ensureArray(exclude)) : []), - /\/node_modules\//, + ...(excludeNodeModules ? [/\/node_modules\//] : []), ], }, }, async handler(code, id, options) { - if (id.includes('/node_modules/')) return + if (excludeNodeModules && id.includes('/node_modules/')) return const [filepath] = id.split('?') if (!filter(filepath)) return