@vitejs/plugin-react 4.3.3 → 4.4.0-beta.1

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
@@ -96,7 +96,7 @@ Here's the [complete list of Babel parser plugins](https://babeljs.io/docs/en/ba
96
96
 
97
97
  ## Middleware mode
98
98
 
99
- In [middleware mode](https://vitejs.dev/config/server-options.html#server-middlewaremode), you should make sure your entry `index.html` file is transformed by Vite. Here's an example for an Express server:
99
+ In [middleware mode](https://vite.dev/config/server-options.html#server-middlewaremode), you should make sure your entry `index.html` file is transformed by Vite. Here's an example for an Express server:
100
100
 
101
101
  ```js
102
102
  app.get('/', async (req, res, next) => {
package/dist/index.cjs CHANGED
@@ -1,89 +1,115 @@
1
1
  'use strict';
2
2
 
3
+ const node_path = require('node:path');
4
+ const node_url = require('node:url');
5
+ const node_fs = require('node:fs');
3
6
  const vite = require('vite');
4
- const fs = require('node:fs');
5
- const path = require('node:path');
6
- const node_module = require('node:module');
7
7
 
8
8
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
10
-
11
- const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
12
- const path__default = /*#__PURE__*/_interopDefaultCompat(path);
13
-
14
9
  const runtimePublicPath = "/@react-refresh";
15
- const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
16
- const reactRefreshDir = path__default.dirname(
17
- _require.resolve("react-refresh/package.json")
18
- );
19
- const runtimeFilePath = path__default.join(
20
- reactRefreshDir,
21
- "cjs/react-refresh-runtime.development.js"
22
- );
23
- const runtimeCode = `
24
- const exports = {}
25
- ${fs__default.readFileSync(runtimeFilePath, "utf-8")}
26
- ${fs__default.readFileSync(_require.resolve("./refreshUtils.js"), "utf-8")}
27
- export default exports
28
- `;
29
- const preambleCode = `
30
- import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}"
31
- RefreshRuntime.injectIntoGlobalHook(window)
32
- window.$RefreshReg$ = () => {}
33
- window.$RefreshSig$ = () => (type) => type
34
- window.__vite_plugin_react_preamble_installed__ = true
35
- `;
36
- const sharedHeader = `
37
- import RefreshRuntime from "${runtimePublicPath}";
38
-
39
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
40
- `.replace(/\n+/g, "");
41
- const functionHeader = `
42
- let prevRefreshReg;
10
+ const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
11
+ const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
12
+ const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
13
+ 1
14
+ )}"
15
+ injectIntoGlobalHook(window);
16
+ window.$RefreshReg$ = () => {};
17
+ window.$RefreshSig$ = () => (type) => type;`;
18
+ const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
19
+ const avoidSourceMapOption = Symbol();
20
+ function addRefreshWrapper(code, map, pluginName, id) {
21
+ const hasRefresh = refreshContentRE.test(code);
22
+ const onlyReactComp = !hasRefresh && reactCompRE.test(code);
23
+ const normalizedMap = map === avoidSourceMapOption ? null : map;
24
+ if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
25
+ const avoidSourceMap = map === avoidSourceMapOption;
26
+ const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
27
+ let newCode = code;
28
+ if (hasRefresh) {
29
+ const refreshHead = removeLineBreaksIfNeeded(
30
+ `let prevRefreshReg;
43
31
  let prevRefreshSig;
44
32
 
45
33
  if (import.meta.hot && !inWebWorker) {
46
- if (!window.__vite_plugin_react_preamble_installed__) {
34
+ if (!window.$RefreshReg$) {
47
35
  throw new Error(
48
- "@vitejs/plugin-react can't detect preamble. Something is wrong. " +
49
- "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201"
36
+ "${pluginName} can't detect preamble. Something is wrong."
50
37
  );
51
38
  }
52
39
 
53
40
  prevRefreshReg = window.$RefreshReg$;
54
41
  prevRefreshSig = window.$RefreshSig$;
55
- window.$RefreshReg$ = (type, id) => {
56
- RefreshRuntime.register(type, __SOURCE__ + " " + id)
57
- };
42
+ window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
58
43
  window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
59
- }`.replace(/\n+/g, "");
60
- const functionFooter = `
44
+ }
45
+
46
+ `,
47
+ avoidSourceMap
48
+ );
49
+ newCode = `${refreshHead}${newCode}
50
+
61
51
  if (import.meta.hot && !inWebWorker) {
62
52
  window.$RefreshReg$ = prevRefreshReg;
63
53
  window.$RefreshSig$ = prevRefreshSig;
64
- }`;
65
- const sharedFooter = (id) => `
54
+ }
55
+ `;
56
+ if (newMap) {
57
+ newMap.mappings = ";".repeat(16) + newMap.mappings;
58
+ }
59
+ }
60
+ const sharedHead = removeLineBreaksIfNeeded(
61
+ `import * as RefreshRuntime from "${runtimePublicPath}";
62
+ const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
63
+
64
+ `,
65
+ avoidSourceMap
66
+ );
67
+ newCode = `${sharedHead}${newCode}
68
+
66
69
  if (import.meta.hot && !inWebWorker) {
67
70
  RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
68
71
  RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
69
- id
70
- )}, currentExports);
72
+ id
73
+ )}, currentExports);
71
74
  import.meta.hot.accept((nextExports) => {
72
75
  if (!nextExports) return;
73
76
  const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
74
- id
75
- )}, currentExports, nextExports);
77
+ id
78
+ )}, currentExports, nextExports);
76
79
  if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
77
80
  });
78
81
  });
79
- }`;
80
- function addRefreshWrapper(code, id) {
81
- return sharedHeader + functionHeader.replace("__SOURCE__", JSON.stringify(id)) + code + functionFooter + sharedFooter(id);
82
82
  }
83
- function addClassComponentRefreshWrapper(code, id) {
84
- return sharedHeader + code + sharedFooter(id);
83
+ `;
84
+ if (newMap) {
85
+ newMap.mappings = ";;;" + newMap.mappings;
86
+ }
87
+ return { code: newCode, map: newMap };
85
88
  }
89
+ function removeLineBreaksIfNeeded(code, enabled) {
90
+ return enabled ? code.replace(/\n/g, "") : code;
91
+ }
92
+
93
+ const silenceUseClientWarning = (userConfig) => ({
94
+ rollupOptions: {
95
+ onwarn(warning, defaultHandler) {
96
+ if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
97
+ return;
98
+ }
99
+ if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
100
+ return;
101
+ }
102
+ if (userConfig.build?.rollupOptions?.onwarn) {
103
+ userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
104
+ } else {
105
+ defaultHandler(warning);
106
+ }
107
+ }
108
+ }
109
+ });
86
110
 
111
+ const _dirname = node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
112
+ const refreshRuntimePath = node_path.join(_dirname, "refresh-runtime.js") ;
87
113
  let babel;
88
114
  async function loadBabel() {
89
115
  if (!babel) {
@@ -91,12 +117,9 @@ async function loadBabel() {
91
117
  }
92
118
  return babel;
93
119
  }
94
- const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
95
- const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
96
120
  const defaultIncludeRE = /\.[tj]sx?$/;
97
121
  const tsRE = /\.tsx?$/;
98
122
  function viteReact(opts = {}) {
99
- let devBase = "/";
100
123
  const filter = vite.createFilter(opts.include ?? defaultIncludeRE, opts.exclude);
101
124
  const jsxImportSource = opts.jsxImportSource ?? "react";
102
125
  const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
@@ -128,7 +151,6 @@ function viteReact(opts = {}) {
128
151
  }
129
152
  },
130
153
  configResolved(config) {
131
- devBase = config.base;
132
154
  projectRoot = config.root;
133
155
  isProduction = config.isProduction;
134
156
  skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
@@ -147,15 +169,12 @@ function viteReact(opts = {}) {
147
169
  }
148
170
  },
149
171
  async transform(code, id, options) {
150
- if (id.includes("/node_modules/"))
151
- return;
172
+ if (id.includes("/node_modules/")) return;
152
173
  const [filepath] = id.split("?");
153
- if (!filter(filepath))
154
- return;
174
+ if (!filter(filepath)) return;
155
175
  const ssr = options?.ssr === true;
156
176
  const babelOptions = (() => {
157
- if (staticBabelOptions)
158
- return staticBabelOptions;
177
+ if (staticBabelOptions) return staticBabelOptions;
159
178
  const newBabelOptions = createBabelOptions(
160
179
  typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
161
180
  );
@@ -196,7 +215,7 @@ function viteReact(opts = {}) {
196
215
  filename: id,
197
216
  sourceFileName: filepath,
198
217
  // Required for esbuild.jsxDev to provide correct line numbers
199
- // This crates issues the react compiler because the re-order is too important
218
+ // This creates issues the react compiler because the re-order is too important
200
219
  // People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
201
220
  retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
202
221
  parserOpts: {
@@ -207,21 +226,23 @@ function viteReact(opts = {}) {
207
226
  },
208
227
  generatorOpts: {
209
228
  ...babelOptions.generatorOpts,
229
+ // import attributes parsing available without plugin since 7.26
230
+ importAttributesKeyword: "with",
210
231
  decoratorsBeforeExport: true
211
232
  },
212
233
  plugins,
213
234
  sourceMaps: true
214
235
  });
215
236
  if (result) {
216
- let code2 = result.code;
217
- if (useFastRefresh) {
218
- if (refreshContentRE.test(code2)) {
219
- code2 = addRefreshWrapper(code2, id);
220
- } else if (reactCompRE.test(code2)) {
221
- code2 = addClassComponentRefreshWrapper(code2, id);
222
- }
237
+ if (!useFastRefresh) {
238
+ return { code: result.code, map: result.map };
223
239
  }
224
- return { code: code2, map: result.map };
240
+ return addRefreshWrapper(
241
+ result.code,
242
+ result.map,
243
+ "@vitejs/plugin-react",
244
+ id
245
+ );
225
246
  }
226
247
  }
227
248
  };
@@ -256,16 +277,19 @@ function viteReact(opts = {}) {
256
277
  },
257
278
  load(id) {
258
279
  if (id === runtimePublicPath) {
259
- return runtimeCode;
280
+ return node_fs.readFileSync(refreshRuntimePath, "utf-8").replace(
281
+ /__README_URL__/g,
282
+ "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react"
283
+ );
260
284
  }
261
285
  },
262
- transformIndexHtml() {
286
+ transformIndexHtml(_, config) {
263
287
  if (!skipFastRefresh)
264
288
  return [
265
289
  {
266
290
  tag: "script",
267
291
  attrs: { type: "module" },
268
- children: preambleCode.replace(`__BASE__`, devBase)
292
+ children: getPreambleCode(config.server.config.base)
269
293
  }
270
294
  ];
271
295
  }
@@ -273,28 +297,10 @@ function viteReact(opts = {}) {
273
297
  return [viteBabel, viteReactRefresh];
274
298
  }
275
299
  viteReact.preambleCode = preambleCode;
276
- const silenceUseClientWarning = (userConfig) => ({
277
- rollupOptions: {
278
- onwarn(warning, defaultHandler) {
279
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
280
- return;
281
- }
282
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
283
- return;
284
- }
285
- if (userConfig.build?.rollupOptions?.onwarn) {
286
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
287
- } else {
288
- defaultHandler(warning);
289
- }
290
- }
291
- }
292
- });
293
300
  const loadedPlugin = /* @__PURE__ */ new Map();
294
301
  function loadPlugin(path) {
295
302
  const cached = loadedPlugin.get(path);
296
- if (cached)
297
- return cached;
303
+ if (cached) return cached;
298
304
  const promise = import(path).then((module) => {
299
305
  const value = module.default || module;
300
306
  loadedPlugin.set(path, value);
@@ -304,17 +310,16 @@ function loadPlugin(path) {
304
310
  return promise;
305
311
  }
306
312
  function createBabelOptions(rawOptions) {
307
- var _a;
308
313
  const babelOptions = {
309
314
  babelrc: false,
310
315
  configFile: false,
311
316
  ...rawOptions
312
317
  };
313
- babelOptions.plugins || (babelOptions.plugins = []);
314
- babelOptions.presets || (babelOptions.presets = []);
315
- babelOptions.overrides || (babelOptions.overrides = []);
316
- babelOptions.parserOpts || (babelOptions.parserOpts = {});
317
- (_a = babelOptions.parserOpts).plugins || (_a.plugins = []);
318
+ babelOptions.plugins ||= [];
319
+ babelOptions.presets ||= [];
320
+ babelOptions.overrides ||= [];
321
+ babelOptions.parserOpts ||= {};
322
+ babelOptions.parserOpts.plugins ||= [];
318
323
  return babelOptions;
319
324
  }
320
325
  function defined(value) {
package/dist/index.d.cts CHANGED
@@ -51,4 +51,5 @@ declare namespace viteReact {
51
51
  var preambleCode: string;
52
52
  }
53
53
 
54
- export { type BabelOptions, type Options, type ReactBabelOptions, type ViteReactPluginApi, viteReact as default };
54
+ export = viteReact;
55
+ export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };
package/dist/index.d.mts CHANGED
@@ -51,4 +51,5 @@ declare namespace viteReact {
51
51
  var preambleCode: string;
52
52
  }
53
53
 
54
- export { type BabelOptions, type Options, type ReactBabelOptions, type ViteReactPluginApi, viteReact as default };
54
+ export { viteReact as default };
55
+ export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };
package/dist/index.d.ts CHANGED
@@ -51,4 +51,5 @@ declare namespace viteReact {
51
51
  var preambleCode: string;
52
52
  }
53
53
 
54
- export { type BabelOptions, type Options, type ReactBabelOptions, type ViteReactPluginApi, viteReact as default };
54
+ export = viteReact;
55
+ export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };
package/dist/index.mjs CHANGED
@@ -1,81 +1,112 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { readFileSync } from 'node:fs';
1
4
  import { createFilter } from 'vite';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { createRequire } from 'node:module';
5
5
 
6
6
  const runtimePublicPath = "/@react-refresh";
7
- const _require = createRequire(import.meta.url);
8
- const reactRefreshDir = path.dirname(
9
- _require.resolve("react-refresh/package.json")
10
- );
11
- const runtimeFilePath = path.join(
12
- reactRefreshDir,
13
- "cjs/react-refresh-runtime.development.js"
14
- );
15
- const runtimeCode = `
16
- const exports = {}
17
- ${fs.readFileSync(runtimeFilePath, "utf-8")}
18
- ${fs.readFileSync(_require.resolve("./refreshUtils.js"), "utf-8")}
19
- export default exports
20
- `;
21
- const preambleCode = `
22
- import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}"
23
- RefreshRuntime.injectIntoGlobalHook(window)
24
- window.$RefreshReg$ = () => {}
25
- window.$RefreshSig$ = () => (type) => type
26
- window.__vite_plugin_react_preamble_installed__ = true
27
- `;
28
- const sharedHeader = `
29
- import RefreshRuntime from "${runtimePublicPath}";
30
-
31
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
32
- `.replace(/\n+/g, "");
33
- const functionHeader = `
34
- let prevRefreshReg;
7
+ const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
8
+ const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
9
+ const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
10
+ 1
11
+ )}"
12
+ injectIntoGlobalHook(window);
13
+ window.$RefreshReg$ = () => {};
14
+ window.$RefreshSig$ = () => (type) => type;`;
15
+ const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
16
+ const avoidSourceMapOption = Symbol();
17
+ function addRefreshWrapper(code, map, pluginName, id) {
18
+ const hasRefresh = refreshContentRE.test(code);
19
+ const onlyReactComp = !hasRefresh && reactCompRE.test(code);
20
+ const normalizedMap = map === avoidSourceMapOption ? null : map;
21
+ if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
22
+ const avoidSourceMap = map === avoidSourceMapOption;
23
+ const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
24
+ let newCode = code;
25
+ if (hasRefresh) {
26
+ const refreshHead = removeLineBreaksIfNeeded(
27
+ `let prevRefreshReg;
35
28
  let prevRefreshSig;
36
29
 
37
30
  if (import.meta.hot && !inWebWorker) {
38
- if (!window.__vite_plugin_react_preamble_installed__) {
31
+ if (!window.$RefreshReg$) {
39
32
  throw new Error(
40
- "@vitejs/plugin-react can't detect preamble. Something is wrong. " +
41
- "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201"
33
+ "${pluginName} can't detect preamble. Something is wrong."
42
34
  );
43
35
  }
44
36
 
45
37
  prevRefreshReg = window.$RefreshReg$;
46
38
  prevRefreshSig = window.$RefreshSig$;
47
- window.$RefreshReg$ = (type, id) => {
48
- RefreshRuntime.register(type, __SOURCE__ + " " + id)
49
- };
39
+ window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
50
40
  window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
51
- }`.replace(/\n+/g, "");
52
- const functionFooter = `
41
+ }
42
+
43
+ `,
44
+ avoidSourceMap
45
+ );
46
+ newCode = `${refreshHead}${newCode}
47
+
53
48
  if (import.meta.hot && !inWebWorker) {
54
49
  window.$RefreshReg$ = prevRefreshReg;
55
50
  window.$RefreshSig$ = prevRefreshSig;
56
- }`;
57
- const sharedFooter = (id) => `
51
+ }
52
+ `;
53
+ if (newMap) {
54
+ newMap.mappings = ";".repeat(16) + newMap.mappings;
55
+ }
56
+ }
57
+ const sharedHead = removeLineBreaksIfNeeded(
58
+ `import * as RefreshRuntime from "${runtimePublicPath}";
59
+ const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
60
+
61
+ `,
62
+ avoidSourceMap
63
+ );
64
+ newCode = `${sharedHead}${newCode}
65
+
58
66
  if (import.meta.hot && !inWebWorker) {
59
67
  RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
60
68
  RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
61
- id
62
- )}, currentExports);
69
+ id
70
+ )}, currentExports);
63
71
  import.meta.hot.accept((nextExports) => {
64
72
  if (!nextExports) return;
65
73
  const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
66
- id
67
- )}, currentExports, nextExports);
74
+ id
75
+ )}, currentExports, nextExports);
68
76
  if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
69
77
  });
70
78
  });
71
- }`;
72
- function addRefreshWrapper(code, id) {
73
- return sharedHeader + functionHeader.replace("__SOURCE__", JSON.stringify(id)) + code + functionFooter + sharedFooter(id);
74
79
  }
75
- function addClassComponentRefreshWrapper(code, id) {
76
- return sharedHeader + code + sharedFooter(id);
80
+ `;
81
+ if (newMap) {
82
+ newMap.mappings = ";;;" + newMap.mappings;
83
+ }
84
+ return { code: newCode, map: newMap };
85
+ }
86
+ function removeLineBreaksIfNeeded(code, enabled) {
87
+ return enabled ? code.replace(/\n/g, "") : code;
77
88
  }
78
89
 
90
+ const silenceUseClientWarning = (userConfig) => ({
91
+ rollupOptions: {
92
+ onwarn(warning, defaultHandler) {
93
+ if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
94
+ return;
95
+ }
96
+ if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
97
+ return;
98
+ }
99
+ if (userConfig.build?.rollupOptions?.onwarn) {
100
+ userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
101
+ } else {
102
+ defaultHandler(warning);
103
+ }
104
+ }
105
+ }
106
+ });
107
+
108
+ const _dirname = dirname(fileURLToPath(import.meta.url));
109
+ const refreshRuntimePath = join(_dirname, "refresh-runtime.js") ;
79
110
  let babel;
80
111
  async function loadBabel() {
81
112
  if (!babel) {
@@ -83,12 +114,9 @@ async function loadBabel() {
83
114
  }
84
115
  return babel;
85
116
  }
86
- const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
87
- const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
88
117
  const defaultIncludeRE = /\.[tj]sx?$/;
89
118
  const tsRE = /\.tsx?$/;
90
119
  function viteReact(opts = {}) {
91
- let devBase = "/";
92
120
  const filter = createFilter(opts.include ?? defaultIncludeRE, opts.exclude);
93
121
  const jsxImportSource = opts.jsxImportSource ?? "react";
94
122
  const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
@@ -120,7 +148,6 @@ function viteReact(opts = {}) {
120
148
  }
121
149
  },
122
150
  configResolved(config) {
123
- devBase = config.base;
124
151
  projectRoot = config.root;
125
152
  isProduction = config.isProduction;
126
153
  skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
@@ -139,15 +166,12 @@ function viteReact(opts = {}) {
139
166
  }
140
167
  },
141
168
  async transform(code, id, options) {
142
- if (id.includes("/node_modules/"))
143
- return;
169
+ if (id.includes("/node_modules/")) return;
144
170
  const [filepath] = id.split("?");
145
- if (!filter(filepath))
146
- return;
171
+ if (!filter(filepath)) return;
147
172
  const ssr = options?.ssr === true;
148
173
  const babelOptions = (() => {
149
- if (staticBabelOptions)
150
- return staticBabelOptions;
174
+ if (staticBabelOptions) return staticBabelOptions;
151
175
  const newBabelOptions = createBabelOptions(
152
176
  typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
153
177
  );
@@ -188,7 +212,7 @@ function viteReact(opts = {}) {
188
212
  filename: id,
189
213
  sourceFileName: filepath,
190
214
  // Required for esbuild.jsxDev to provide correct line numbers
191
- // This crates issues the react compiler because the re-order is too important
215
+ // This creates issues the react compiler because the re-order is too important
192
216
  // People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
193
217
  retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
194
218
  parserOpts: {
@@ -199,21 +223,23 @@ function viteReact(opts = {}) {
199
223
  },
200
224
  generatorOpts: {
201
225
  ...babelOptions.generatorOpts,
226
+ // import attributes parsing available without plugin since 7.26
227
+ importAttributesKeyword: "with",
202
228
  decoratorsBeforeExport: true
203
229
  },
204
230
  plugins,
205
231
  sourceMaps: true
206
232
  });
207
233
  if (result) {
208
- let code2 = result.code;
209
- if (useFastRefresh) {
210
- if (refreshContentRE.test(code2)) {
211
- code2 = addRefreshWrapper(code2, id);
212
- } else if (reactCompRE.test(code2)) {
213
- code2 = addClassComponentRefreshWrapper(code2, id);
214
- }
234
+ if (!useFastRefresh) {
235
+ return { code: result.code, map: result.map };
215
236
  }
216
- return { code: code2, map: result.map };
237
+ return addRefreshWrapper(
238
+ result.code,
239
+ result.map,
240
+ "@vitejs/plugin-react",
241
+ id
242
+ );
217
243
  }
218
244
  }
219
245
  };
@@ -248,16 +274,19 @@ function viteReact(opts = {}) {
248
274
  },
249
275
  load(id) {
250
276
  if (id === runtimePublicPath) {
251
- return runtimeCode;
277
+ return readFileSync(refreshRuntimePath, "utf-8").replace(
278
+ /__README_URL__/g,
279
+ "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react"
280
+ );
252
281
  }
253
282
  },
254
- transformIndexHtml() {
283
+ transformIndexHtml(_, config) {
255
284
  if (!skipFastRefresh)
256
285
  return [
257
286
  {
258
287
  tag: "script",
259
288
  attrs: { type: "module" },
260
- children: preambleCode.replace(`__BASE__`, devBase)
289
+ children: getPreambleCode(config.server.config.base)
261
290
  }
262
291
  ];
263
292
  }
@@ -265,28 +294,10 @@ function viteReact(opts = {}) {
265
294
  return [viteBabel, viteReactRefresh];
266
295
  }
267
296
  viteReact.preambleCode = preambleCode;
268
- const silenceUseClientWarning = (userConfig) => ({
269
- rollupOptions: {
270
- onwarn(warning, defaultHandler) {
271
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
272
- return;
273
- }
274
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
275
- return;
276
- }
277
- if (userConfig.build?.rollupOptions?.onwarn) {
278
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
279
- } else {
280
- defaultHandler(warning);
281
- }
282
- }
283
- }
284
- });
285
297
  const loadedPlugin = /* @__PURE__ */ new Map();
286
298
  function loadPlugin(path) {
287
299
  const cached = loadedPlugin.get(path);
288
- if (cached)
289
- return cached;
300
+ if (cached) return cached;
290
301
  const promise = import(path).then((module) => {
291
302
  const value = module.default || module;
292
303
  loadedPlugin.set(path, value);
@@ -296,17 +307,16 @@ function loadPlugin(path) {
296
307
  return promise;
297
308
  }
298
309
  function createBabelOptions(rawOptions) {
299
- var _a;
300
310
  const babelOptions = {
301
311
  babelrc: false,
302
312
  configFile: false,
303
313
  ...rawOptions
304
314
  };
305
- babelOptions.plugins || (babelOptions.plugins = []);
306
- babelOptions.presets || (babelOptions.presets = []);
307
- babelOptions.overrides || (babelOptions.overrides = []);
308
- babelOptions.parserOpts || (babelOptions.parserOpts = {});
309
- (_a = babelOptions.parserOpts).plugins || (_a.plugins = []);
315
+ babelOptions.plugins ||= [];
316
+ babelOptions.presets ||= [];
317
+ babelOptions.overrides ||= [];
318
+ babelOptions.parserOpts ||= {};
319
+ babelOptions.parserOpts.plugins ||= [];
310
320
  return babelOptions;
311
321
  }
312
322
  function defined(value) {