@vitejs/plugin-react 6.1.1 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,8 +8,8 @@ The default Vite plugin for React projects.
8
8
 
9
9
  ```js
10
10
  // vite.config.js
11
- import { defineConfig } from 'vite'
12
11
  import react from '@vitejs/plugin-react'
12
+ import { defineConfig } from 'vite'
13
13
 
14
14
  export default defineConfig({
15
15
  plugins: [react()],
@@ -23,9 +23,9 @@ export default defineConfig({
23
23
  Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to add fast refresh to `.mdx` files:
24
24
 
25
25
  ```js
26
- import { defineConfig } from 'vite'
27
- import react from '@vitejs/plugin-react'
28
26
  import mdx from '@mdx-js/rollup'
27
+ import react from '@vitejs/plugin-react'
28
+ import { defineConfig } from 'vite'
29
29
 
30
30
  export default defineConfig({
31
31
  plugins: [
@@ -41,8 +41,8 @@ The default value is `/node_modules/`. You may use it to exclude JSX/TSX files t
41
41
  Except if explicitly desired, you should keep `node_modules` in the exclude list:
42
42
 
43
43
  ```js
44
- import { defineConfig } from 'vite'
45
44
  import react from '@vitejs/plugin-react'
45
+ import { defineConfig } from 'vite'
46
46
 
47
47
  export default defineConfig({
48
48
  plugins: [
@@ -92,8 +92,8 @@ npm install -D oxc-transform-react
92
92
 
93
93
  ```js
94
94
  // vite.config.js
95
- import { defineConfig } from 'vite'
96
95
  import react from '@vitejs/plugin-react'
96
+ import { defineConfig } from 'vite'
97
97
 
98
98
  export default defineConfig({
99
99
  plugins: [react({ compiler: true })],
@@ -128,9 +128,9 @@ npm install -D @types/babel__core
128
128
 
129
129
  ```js
130
130
  // vite.config.js
131
- import { defineConfig } from 'vite'
132
- import react, { reactCompilerPreset } from '@vitejs/plugin-react'
133
131
  import babel from '@rolldown/plugin-babel'
132
+ import react, { reactCompilerPreset } from '@vitejs/plugin-react'
133
+ import { defineConfig } from 'vite'
134
134
 
135
135
  export default defineConfig({
136
136
  plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
package/dist/index.d.ts CHANGED
@@ -1,18 +1,16 @@
1
1
  import { Plugin } from "vite";
2
2
  import { ReactCompilerBabelPluginOptions, ReactCompilerOptions, RolldownBabelPreset } from "#optionalTypes";
3
- //#region src/reactCompilerPreset.d.ts
4
- declare const reactCompilerPreset: (options?: ReactCompilerBabelPluginOptions) => RolldownBabelPreset;
5
- //#endregion
6
- //#region src/index.d.ts
3
+ export declare const reactCompilerPreset: (options?: ReactCompilerBabelPluginOptions) => RolldownBabelPreset;
7
4
  interface ReactCompilerPluginOptions extends ReactCompilerOptions {
8
5
  /**
9
6
  * Log recoverable React Compiler diagnostics through Vite.
10
7
  * Fatal diagnostics are always logged and fail the transform.
11
8
  * @default false
9
+ * @deprecated Use `reportDiagnostics` instead
12
10
  */
13
11
  logDiagnostics?: boolean;
14
12
  }
15
- interface Options {
13
+ export interface Options {
16
14
  /**
17
15
  * Can be used to process extra files like `.mdx`
18
16
  * @example include: /\.(mdx|js|jsx|ts|tsx)$/
@@ -26,6 +24,16 @@ interface Options {
26
24
  * @default /\/node_modules\//
27
25
  */
28
26
  exclude?: string | RegExp | Array<string | RegExp>;
27
+ /**
28
+ * Can be used to skip fast refresh for certain files that won't run in the browser.
29
+ * @example options.include
30
+ */
31
+ refreshInclude?: string | RegExp | Array<string | RegExp>;
32
+ /**
33
+ * Can be used to skip fast refresh for certain files that won't run in the browser.
34
+ * @default options.exclude
35
+ */
36
+ refreshExclude?: string | RegExp | Array<string | RegExp>;
29
37
  /**
30
38
  * Control where the JSX factory is imported from.
31
39
  * https://oxc.rs/docs/guide/usage/transformer/jsx.html#import-source
@@ -36,7 +44,7 @@ interface Options {
36
44
  * Note: Skipping React import with classic runtime is not supported from v4
37
45
  * @default "automatic"
38
46
  */
39
- jsxRuntime?: 'classic' | 'automatic';
47
+ jsxRuntime?: "classic" | "automatic";
40
48
  /**
41
49
  * React Fast Refresh runtime URL prefix.
42
50
  * Useful in a module federation context to enable HMR by specifying
@@ -54,9 +62,8 @@ interface Options {
54
62
  compiler?: boolean | ReactCompilerPluginOptions;
55
63
  }
56
64
  declare function viteReact(opts?: Options): Plugin[];
57
- declare namespace viteReact {
58
- var preambleCode: string;
59
- }
65
+ declare const viteReactWithPreamble: typeof viteReact & {
66
+ preambleCode: string;
67
+ };
60
68
  declare function viteReactForCjs(this: unknown, options: Options): Plugin[];
61
- //#endregion
62
- export { Options, type ReactCompilerPluginOptions as ReactCompilerOptions, viteReact as default, viteReactForCjs as "module.exports", reactCompilerPreset };
69
+ export { type ReactCompilerPluginOptions as ReactCompilerOptions, viteReactWithPreamble as default, viteReactForCjs as "module.exports" };
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@ import { readFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { exactRegex, makeIdFiltersToMatchWithQuery } from "@rolldown/pluginutils";
5
+ import { createFilter } from "vite";
5
6
  import { reactRefreshWrapperPlugin } from "vite/internal";
6
- //#region ../common/refresh-utils.ts
7
+ // ../common/refresh-utils.ts
7
8
  const runtimePublicPath = "/@react-refresh";
8
9
  const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
9
10
  injectIntoGlobalHook(window);
@@ -31,16 +32,14 @@ function virtualPreamblePlugin({ name, isEnabled }) {
31
32
  }
32
33
  };
33
34
  }
34
- //#endregion
35
- //#region ../common/warning.ts
35
+ // ../common/warning.ts
36
36
  const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
37
37
  if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
38
38
  if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
39
39
  if (userConfig.build?.rollupOptions?.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
40
40
  else defaultHandler(warning);
41
41
  } } });
42
- //#endregion
43
- //#region src/reactCompilerPreset.ts
42
+ // src/reactCompilerPreset.ts
44
43
  const defaultCodeFilter = /forwardRef|memo|\b(?:[A-Z]|use[A-Z0-9])/;
45
44
  const reactCompilerPreset = (options = {}) => ({
46
45
  preset: () => ({ plugins: [[fileURLToPath(import.meta.resolve("babel-plugin-react-compiler")), options]] }),
@@ -50,8 +49,7 @@ const reactCompilerPreset = (options = {}) => ({
50
49
  optimizeDeps: { include: options.target === "17" || options.target === "18" ? ["react-compiler-runtime"] : ["react/compiler-runtime"] }
51
50
  }
52
51
  });
53
- //#endregion
54
- //#region src/index.ts
52
+ // src/index.ts
55
53
  const _dirname = dirname(fileURLToPath(import.meta.url));
56
54
  const refreshRuntimePath = join(_dirname, "refresh-runtime.js");
57
55
  const defaultIncludeRE = /\.[tj]sx?$/;
@@ -59,6 +57,8 @@ const defaultExcludeRE = /\/node_modules\//;
59
57
  function viteReact(opts = {}) {
60
58
  const include = opts.include ?? defaultIncludeRE;
61
59
  const exclude = opts.exclude ?? defaultExcludeRE;
60
+ const jsxRefreshInclude = makeIdFiltersToMatchWithQuery(opts.refreshInclude ?? include);
61
+ const jsxRefreshExclude = makeIdFiltersToMatchWithQuery(opts.refreshExclude ?? exclude);
62
62
  const jsxImportSource = opts.jsxImportSource ?? "react";
63
63
  const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
64
64
  const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
@@ -79,8 +79,8 @@ function viteReact(opts = {}) {
79
79
  runtime: "classic",
80
80
  refresh
81
81
  },
82
- jsxRefreshInclude: makeIdFiltersToMatchWithQuery(include),
83
- jsxRefreshExclude: makeIdFiltersToMatchWithQuery(exclude)
82
+ jsxRefreshInclude,
83
+ jsxRefreshExclude
84
84
  } };
85
85
  else return {
86
86
  oxc: {
@@ -89,8 +89,8 @@ function viteReact(opts = {}) {
89
89
  importSource: opts.jsxImportSource,
90
90
  refresh
91
91
  },
92
- jsxRefreshInclude: makeIdFiltersToMatchWithQuery(include),
93
- jsxRefreshExclude: makeIdFiltersToMatchWithQuery(exclude)
92
+ jsxRefreshInclude,
93
+ jsxRefreshExclude
94
94
  },
95
95
  optimizeDeps: { rolldownOptions: { transform: { jsx: { runtime: "automatic" } } } }
96
96
  };
@@ -119,8 +119,8 @@ function viteReact(opts = {}) {
119
119
  if (env.config.consumer !== "client" || skipFastRefresh) return false;
120
120
  return reactRefreshWrapperPlugin({
121
121
  cwd: process.cwd(),
122
- include: makeIdFiltersToMatchWithQuery(include),
123
- exclude: makeIdFiltersToMatchWithQuery(exclude),
122
+ include: jsxRefreshInclude,
123
+ exclude: jsxRefreshExclude,
124
124
  jsxImportSource,
125
125
  reactRefreshHost: opts.reactRefreshHost ?? ""
126
126
  });
@@ -198,6 +198,10 @@ function createReactCompilerPlugin({ logDiagnostics, ...reactCompilerOptions },
198
198
  let jsxDevelopment = false;
199
199
  let compiler;
200
200
  const runtime = reactCompilerOptions.target === "17" || reactCompilerOptions.target === "18" ? "react-compiler-runtime" : "react/compiler-runtime";
201
+ const jsxImportSource = reactOptions.jsxImportSource ?? "react";
202
+ const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
203
+ const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
204
+ const jsxRefreshFilter = reactOptions.refreshInclude || reactOptions.refreshExclude ? createFilter(reactOptions.refreshInclude, reactOptions.refreshExclude) : void 0;
201
205
  const loadCompiler = async (onError) => {
202
206
  if (compiler) return compiler;
203
207
  try {
@@ -222,7 +226,10 @@ function createReactCompilerPlugin({ logDiagnostics, ...reactCompilerOptions },
222
226
  exclude: makeIdFiltersToMatchWithQuery(exclude)
223
227
  } },
224
228
  async handler(code, id) {
229
+ const [filepath] = id.split("?");
230
+ const isJSX = filepath.endsWith("x");
225
231
  const isClient = this.environment?.config.consumer !== "server";
232
+ const refreshEnabled = isClient && isFastRefreshEnabled() && (jsxRefreshFilter && !jsxRefreshFilter(id) || !(isJSX || code.includes(jsxImportRuntime) || code.includes(jsxImportDevRuntime)));
226
233
  const shouldCompile = isClient && (reactCompilerOptions.compilationMode === "annotation" ? /['"]use memo['"]/.test(code) : defaultCodeFilter.test(code));
227
234
  const { transform } = compiler ?? await loadCompiler((message) => this.error(message));
228
235
  const result = await transform(id.split("?")[0], code, {
@@ -230,14 +237,17 @@ function createReactCompilerPlugin({ logDiagnostics, ...reactCompilerOptions },
230
237
  runtime: reactOptions.jsxRuntime,
231
238
  development: jsxDevelopment,
232
239
  importSource: reactOptions.jsxImportSource,
233
- refresh: isClient && isFastRefreshEnabled()
240
+ refresh: refreshEnabled
234
241
  },
235
- reactCompiler: shouldCompile ? reactCompilerOptions : false,
242
+ reactCompiler: !shouldCompile ? false : logDiagnostics ? {
243
+ ...reactCompilerOptions,
244
+ reportDiagnostics: true
245
+ } : reactCompilerOptions,
236
246
  sourcemap: this.environment ? this.environment.config.command !== "build" || !!this.environment.config.build.sourcemap : true
237
247
  });
238
248
  const diagnostics = result.errors.map((error) => `${error.message}${error.codeframe ? `\n${error.codeframe}` : ""}`);
239
249
  if (result.fatal) this.error(diagnostics.join("\n\n") || "React Compiler transform failed.");
240
- if (logDiagnostics) for (const diagnostic of diagnostics) this.warn(diagnostic);
250
+ for (const diagnostic of diagnostics) this.warn(diagnostic);
241
251
  return {
242
252
  code: result.code,
243
253
  map: result.map
@@ -246,7 +256,7 @@ function createReactCompilerPlugin({ logDiagnostics, ...reactCompilerOptions },
246
256
  }
247
257
  };
248
258
  }
249
- viteReact.preambleCode = preambleCode;
259
+ const viteReactWithPreamble = Object.assign(viteReact, { preambleCode });
250
260
  function viteReactForCjs(options) {
251
261
  return viteReact.call(this, options);
252
262
  }
@@ -254,5 +264,4 @@ Object.assign(viteReactForCjs, {
254
264
  default: viteReactForCjs,
255
265
  reactCompilerPreset
256
266
  });
257
- //#endregion
258
- export { viteReact as default, viteReactForCjs as "module.exports", reactCompilerPreset };
267
+ export { viteReactWithPreamble as default, viteReactForCjs as "module.exports", reactCompilerPreset };
@@ -1,5 +1,5 @@
1
1
  /* global window */
2
- /* eslint-disable eqeqeq, prefer-const, @typescript-eslint/no-empty-function */
2
+ /* oxlint-disable eqeqeq, prefer-const, no-empty-function, no-unused-vars, typescript/no-implied-eval */
3
3
 
4
4
  /*! Copyright (c) Meta Platforms, Inc. and affiliates. **/
5
5
  /**
@@ -112,6 +112,29 @@ function canPreserveStateBetween(prevType, nextType) {
112
112
  if (isReactClass(prevType) || isReactClass(nextType)) {
113
113
  return false
114
114
  }
115
+ // A fiber's tag is derived from the kind of its type (a plain function
116
+ // vs memo vs forwardRef), and the reconciler can only swap implementations
117
+ // in place within the same tag. If the kind changed, the tree must remount.
118
+ if (typeof prevType !== typeof nextType) {
119
+ return false
120
+ }
121
+ if (typeof prevType === 'object' && prevType !== null && nextType !== null) {
122
+ if (
123
+ getProperty(prevType, '$$typeof') !== getProperty(nextType, '$$typeof')
124
+ ) {
125
+ return false
126
+ }
127
+ // Switching from SimpleMemoComponent to MemoComponent requires a remount;
128
+ // for symmetry, remount for the reverse too.
129
+ if (getProperty(prevType, '$$typeof') === REACT_MEMO_TYPE) {
130
+ if (
131
+ (getProperty(prevType, 'compare') === null) !==
132
+ (getProperty(nextType, 'compare') === null)
133
+ ) {
134
+ return false
135
+ }
136
+ }
137
+ }
115
138
  if (haveEqualSignatures(prevType, nextType)) {
116
139
  return true
117
140
  }
@@ -349,6 +372,7 @@ export function injectIntoGlobalHook(globalObject) {
349
372
  // Here, we just want to get a reference to scheduleRefresh.
350
373
  const oldInject = hook.inject
351
374
  hook.inject = function (injected) {
375
+ // oxlint-disable-next-line prefer-rest-params
352
376
  const id = oldInject.apply(this, arguments)
353
377
  if (
354
378
  typeof injected.scheduleRefresh === 'function' &&
@@ -385,6 +409,7 @@ export function injectIntoGlobalHook(globalObject) {
385
409
  rootElements.set(root, children)
386
410
  }
387
411
  }
412
+ // oxlint-disable-next-line prefer-rest-params
388
413
  return oldOnScheduleFiberRoot.apply(this, arguments)
389
414
  }
390
415
  hook.onCommitFiberRoot = function (id, root, maybePriorityLevel, didError) {
@@ -437,6 +462,7 @@ export function injectIntoGlobalHook(globalObject) {
437
462
  }
438
463
 
439
464
  // Always call the decorated DevTools hook.
465
+ // oxlint-disable-next-line prefer-rest-params
440
466
  return oldOnCommitFiberRoot.apply(this, arguments)
441
467
  }
442
468
  }
@@ -609,50 +635,49 @@ export function validateRefreshBoundaryAndEnqueueUpdate(
609
635
  prevExports,
610
636
  nextExports,
611
637
  ) {
638
+ let hasExports = false
612
639
  const ignoredExports = window.__getReactRefreshIgnoredExports?.({ id }) ?? []
613
- if (
614
- predicateOnExport(
615
- ignoredExports,
616
- prevExports,
617
- (key) => key in nextExports,
618
- ) !== true
619
- ) {
620
- return 'Could not Fast Refresh (export removed)'
621
- }
622
- if (
623
- predicateOnExport(
624
- ignoredExports,
625
- nextExports,
626
- (key) => key in prevExports,
627
- ) !== true
628
- ) {
629
- return 'Could not Fast Refresh (new export)'
630
- }
631
640
 
632
- let hasExports = false
633
- const allExportsAreComponentsOrUnchanged = predicateOnExport(
634
- ignoredExports,
635
- nextExports,
636
- (key, value) => {
637
- hasExports = true
638
- if (isLikelyComponentType(value)) return true
639
- if (isCompoundComponent(value)) return true
640
- return prevExports[key] === nextExports[key]
641
- },
642
- )
643
- if (hasExports && allExportsAreComponentsOrUnchanged === true) {
644
- enqueueUpdate()
645
- } else {
646
- return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`
641
+ for (const key in prevExports) {
642
+ if (ignoredExports.includes(key)) continue
643
+ if (!(key in nextExports)) {
644
+ return `Could not Fast Refresh (export "${key}" removed)`
645
+ }
647
646
  }
648
- }
649
647
 
650
- function predicateOnExport(ignoredExports, moduleExports, predicate) {
651
- for (const key in moduleExports) {
648
+ for (const key in nextExports) {
652
649
  if (ignoredExports.includes(key)) continue
653
- if (!predicate(key, moduleExports[key])) return key
650
+ hasExports = true
651
+ if (!(key in prevExports)) {
652
+ return `Could not Fast Refresh (export "${key}" added)`
653
+ }
654
+ if (isLikelyComponentType(nextExports[key])) continue
655
+ if (isCompoundComponent(nextExports[key])) {
656
+ if (!isCompoundComponent(prevExports[key])) {
657
+ return `Could not Fast Refresh (compound component "${key}" added)`
658
+ }
659
+ for (const subKey in prevExports[key]) {
660
+ if (!(subKey in nextExports[key])) {
661
+ return `Could not Fast Refresh (compound component "${key}.${subKey}" removed)`
662
+ }
663
+ }
664
+ for (const subKey in nextExports[key]) {
665
+ if (!(subKey in prevExports[key])) {
666
+ return `Could not Fast Refresh (compound component "${key}.${subKey}" added)`
667
+ }
668
+ }
669
+ continue
670
+ }
671
+ if (prevExports[key] !== nextExports[key]) {
672
+ return `Could not Fast Refresh ("${key}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`
673
+ }
674
+ }
675
+
676
+ if (hasExports) {
677
+ enqueueUpdate()
678
+ } else {
679
+ return `No exports`
654
680
  }
655
- return true
656
681
  }
657
682
 
658
683
  // Hides vite-ignored dynamic import so that Vite can skip analysis if no other
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-react",
3
- "version": "6.1.1",
3
+ "version": "6.2.0",
4
4
  "description": "The default Vite plugin for React projects",
5
5
  "keywords": [
6
6
  "fast refresh",
@@ -46,21 +46,20 @@
46
46
  "@rolldown/pluginutils": "^1.0.1"
47
47
  },
48
48
  "devDependencies": {
49
- "@babel/core": "8.0.1",
50
- "@rolldown/plugin-babel": "^0.2.3",
49
+ "@rolldown/plugin-babel": "^0.3.0",
51
50
  "@vitejs/react-common": "workspace:*",
52
51
  "babel-plugin-react-compiler": "^1.0.0",
53
- "oxc-transform-react": "^0.147.0",
54
- "react": "^19.2.8",
55
- "react-dom": "^19.2.8",
56
- "rolldown": "^1.2.6",
57
- "tsdown": "^0.22.14",
58
- "vite": "^8.2.2"
52
+ "oxc-transform-react": "^0.156.0",
53
+ "react": "^19.3.1",
54
+ "react-dom": "^19.3.1",
55
+ "rolldown": "^1.2.16",
56
+ "tsdown": "^0.23.4",
57
+ "vite": "^8.3.5"
59
58
  },
60
59
  "peerDependencies": {
61
- "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
60
+ "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0",
62
61
  "babel-plugin-react-compiler": "^1.0.0",
63
- "oxc-transform-react": "^0.145.0",
62
+ "oxc-transform-react": ">=0.152.0 <0.157.0",
64
63
  "vite": "^8.0.0"
65
64
  },
66
65
  "peerDependenciesMeta": {
@@ -1,4 +1,4 @@
1
- /* eslint-disable @typescript-eslint/ban-ts-comment */
1
+ /* oxlint-disable @typescript-eslint/ban-ts-comment */
2
2
 
3
3
  // @ts-ignore --- `@rolldown/plugin-babel` is an optional peer dependency, so this may cause an error
4
4
  import type * as pluginBabel from '@rolldown/plugin-babel'