@vitejs/plugin-react 4.3.4 → 4.4.0-beta.2

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/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, reactRefreshHost = "") {
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 "${reactRefreshHost}${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: {
@@ -207,15 +231,16 @@ function viteReact(opts = {}) {
207
231
  sourceMaps: true
208
232
  });
209
233
  if (result) {
210
- let code2 = result.code;
211
- if (useFastRefresh) {
212
- if (refreshContentRE.test(code2)) {
213
- code2 = addRefreshWrapper(code2, id);
214
- } else if (reactCompRE.test(code2)) {
215
- code2 = addClassComponentRefreshWrapper(code2, id);
216
- }
234
+ if (!useFastRefresh) {
235
+ return { code: result.code, map: result.map };
217
236
  }
218
- return { code: code2, map: result.map };
237
+ return addRefreshWrapper(
238
+ result.code,
239
+ result.map,
240
+ "@vitejs/plugin-react",
241
+ id,
242
+ opts.reactRefreshHost
243
+ );
219
244
  }
220
245
  }
221
246
  };
@@ -250,16 +275,19 @@ function viteReact(opts = {}) {
250
275
  },
251
276
  load(id) {
252
277
  if (id === runtimePublicPath) {
253
- return runtimeCode;
278
+ return readFileSync(refreshRuntimePath, "utf-8").replace(
279
+ /__README_URL__/g,
280
+ "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react"
281
+ );
254
282
  }
255
283
  },
256
- transformIndexHtml() {
284
+ transformIndexHtml(_, config) {
257
285
  if (!skipFastRefresh)
258
286
  return [
259
287
  {
260
288
  tag: "script",
261
289
  attrs: { type: "module" },
262
- children: preambleCode.replace(`__BASE__`, devBase)
290
+ children: getPreambleCode(config.server.config.base)
263
291
  }
264
292
  ];
265
293
  }
@@ -267,28 +295,10 @@ function viteReact(opts = {}) {
267
295
  return [viteBabel, viteReactRefresh];
268
296
  }
269
297
  viteReact.preambleCode = preambleCode;
270
- const silenceUseClientWarning = (userConfig) => ({
271
- rollupOptions: {
272
- onwarn(warning, defaultHandler) {
273
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
274
- return;
275
- }
276
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
277
- return;
278
- }
279
- if (userConfig.build?.rollupOptions?.onwarn) {
280
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
281
- } else {
282
- defaultHandler(warning);
283
- }
284
- }
285
- }
286
- });
287
298
  const loadedPlugin = /* @__PURE__ */ new Map();
288
299
  function loadPlugin(path) {
289
300
  const cached = loadedPlugin.get(path);
290
- if (cached)
291
- return cached;
301
+ if (cached) return cached;
292
302
  const promise = import(path).then((module) => {
293
303
  const value = module.default || module;
294
304
  loadedPlugin.set(path, value);
@@ -298,17 +308,16 @@ function loadPlugin(path) {
298
308
  return promise;
299
309
  }
300
310
  function createBabelOptions(rawOptions) {
301
- var _a;
302
311
  const babelOptions = {
303
312
  babelrc: false,
304
313
  configFile: false,
305
314
  ...rawOptions
306
315
  };
307
- babelOptions.plugins || (babelOptions.plugins = []);
308
- babelOptions.presets || (babelOptions.presets = []);
309
- babelOptions.overrides || (babelOptions.overrides = []);
310
- babelOptions.parserOpts || (babelOptions.parserOpts = {});
311
- (_a = babelOptions.parserOpts).plugins || (_a.plugins = []);
316
+ babelOptions.plugins ||= [];
317
+ babelOptions.presets ||= [];
318
+ babelOptions.overrides ||= [];
319
+ babelOptions.parserOpts ||= {};
320
+ babelOptions.parserOpts.plugins ||= [];
312
321
  return babelOptions;
313
322
  }
314
323
  function defined(value) {