@vitejs/plugin-react 4.6.0 → 4.7.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/dist/index.d.mts DELETED
@@ -1,67 +0,0 @@
1
- import { TransformOptions, ParserOptions } from '@babel/core';
2
- import { PluginOption, ResolvedConfig } from 'vite';
3
-
4
- interface Options {
5
- include?: string | RegExp | Array<string | RegExp>;
6
- exclude?: string | RegExp | Array<string | RegExp>;
7
- /**
8
- * Control where the JSX factory is imported from.
9
- * https://esbuild.github.io/api/#jsx-import-source
10
- * @default 'react'
11
- */
12
- jsxImportSource?: string;
13
- /**
14
- * Note: Skipping React import with classic runtime is not supported from v4
15
- * @default "automatic"
16
- */
17
- jsxRuntime?: 'classic' | 'automatic';
18
- /**
19
- * Babel configuration applied in both dev and prod.
20
- */
21
- babel?: BabelOptions | ((id: string, options: {
22
- ssr?: boolean;
23
- }) => BabelOptions);
24
- /**
25
- * React Fast Refresh runtime URL prefix.
26
- * Useful in a module federation context to enable HMR by specifying
27
- * the host application URL in the Vite config of a remote application.
28
- * @example
29
- * reactRefreshHost: 'http://localhost:3000'
30
- */
31
- reactRefreshHost?: string;
32
- /**
33
- * If set, disables the recommendation to use `@vitejs/plugin-react-oxc`
34
- */
35
- disableOxcRecommendation?: boolean;
36
- }
37
- type BabelOptions = Omit<TransformOptions, 'ast' | 'filename' | 'root' | 'sourceFileName' | 'sourceMaps' | 'inputSourceMap'>;
38
- /**
39
- * The object type used by the `options` passed to plugins with
40
- * an `api.reactBabel` method.
41
- */
42
- interface ReactBabelOptions extends BabelOptions {
43
- plugins: Extract<BabelOptions['plugins'], any[]>;
44
- presets: Extract<BabelOptions['presets'], any[]>;
45
- overrides: Extract<BabelOptions['overrides'], any[]>;
46
- parserOpts: ParserOptions & {
47
- plugins: Extract<ParserOptions['plugins'], any[]>;
48
- };
49
- }
50
- type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void;
51
- type ReactBabelHookContext = {
52
- ssr: boolean;
53
- id: string;
54
- };
55
- type ViteReactPluginApi = {
56
- /**
57
- * Manipulate the Babel options of `@vitejs/plugin-react`
58
- */
59
- reactBabel?: ReactBabelHook;
60
- };
61
- declare function viteReact(opts?: Options): PluginOption[];
62
- declare namespace viteReact {
63
- var preambleCode: string;
64
- }
65
-
66
- export { viteReact as default };
67
- export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };
package/dist/index.mjs DELETED
@@ -1,403 +0,0 @@
1
- import { dirname, join } from 'node:path';
2
- import { fileURLToPath } from 'node:url';
3
- import { readFileSync } from 'node:fs';
4
- import * as vite from 'vite';
5
- import { createFilter } from 'vite';
6
- import { makeIdFiltersToMatchWithQuery, exactRegex } from '@rolldown/pluginutils';
7
-
8
- const runtimePublicPath = "/@react-refresh";
9
- const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
10
- const refreshContentRE = /\$RefreshReg\$\(/;
11
- const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
12
- 1
13
- )}";
14
- injectIntoGlobalHook(window);
15
- window.$RefreshReg$ = () => {};
16
- window.$RefreshSig$ = () => (type) => type;`;
17
- const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
18
- const avoidSourceMapOption = Symbol();
19
- function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
20
- const hasRefresh = refreshContentRE.test(code);
21
- const onlyReactComp = !hasRefresh && reactCompRE.test(code);
22
- const normalizedMap = map === avoidSourceMapOption ? null : map;
23
- if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
24
- const avoidSourceMap = map === avoidSourceMapOption;
25
- const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
26
- let newCode = code;
27
- if (hasRefresh) {
28
- const refreshHead = removeLineBreaksIfNeeded(
29
- `let prevRefreshReg;
30
- let prevRefreshSig;
31
-
32
- if (import.meta.hot && !inWebWorker) {
33
- if (!window.$RefreshReg$) {
34
- throw new Error(
35
- "${pluginName} can't detect preamble. Something is wrong."
36
- );
37
- }
38
-
39
- prevRefreshReg = window.$RefreshReg$;
40
- prevRefreshSig = window.$RefreshSig$;
41
- window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
42
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
43
- }
44
-
45
- `,
46
- avoidSourceMap
47
- );
48
- newCode = `${refreshHead}${newCode}
49
-
50
- if (import.meta.hot && !inWebWorker) {
51
- window.$RefreshReg$ = prevRefreshReg;
52
- window.$RefreshSig$ = prevRefreshSig;
53
- }
54
- `;
55
- if (newMap) {
56
- newMap.mappings = ";".repeat(16) + newMap.mappings;
57
- }
58
- }
59
- const sharedHead = removeLineBreaksIfNeeded(
60
- `import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
61
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
62
-
63
- `,
64
- avoidSourceMap
65
- );
66
- newCode = `${sharedHead}${newCode}
67
-
68
- if (import.meta.hot && !inWebWorker) {
69
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
70
- RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
71
- id
72
- )}, currentExports);
73
- import.meta.hot.accept((nextExports) => {
74
- if (!nextExports) return;
75
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
76
- id
77
- )}, currentExports, nextExports);
78
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
79
- });
80
- });
81
- }
82
- `;
83
- if (newMap) {
84
- newMap.mappings = ";;;" + newMap.mappings;
85
- }
86
- return { code: newCode, map: newMap };
87
- }
88
- function removeLineBreaksIfNeeded(code, enabled) {
89
- return enabled ? code.replace(/\n/g, "") : code;
90
- }
91
-
92
- const silenceUseClientWarning = (userConfig) => ({
93
- rollupOptions: {
94
- onwarn(warning, defaultHandler) {
95
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
96
- return;
97
- }
98
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
99
- return;
100
- }
101
- if (userConfig.build?.rollupOptions?.onwarn) {
102
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
103
- } else {
104
- defaultHandler(warning);
105
- }
106
- }
107
- }
108
- });
109
-
110
- const _dirname = dirname(fileURLToPath(import.meta.url));
111
- const refreshRuntimePath = join(_dirname, "refresh-runtime.js") ;
112
- let babel;
113
- async function loadBabel() {
114
- if (!babel) {
115
- babel = await import('@babel/core');
116
- }
117
- return babel;
118
- }
119
- const defaultIncludeRE = /\.[tj]sx?$/;
120
- const tsRE = /\.tsx?$/;
121
- function viteReact(opts = {}) {
122
- const include = opts.include ?? defaultIncludeRE;
123
- const exclude = opts.exclude;
124
- const filter = createFilter(include, exclude);
125
- const jsxImportSource = opts.jsxImportSource ?? "react";
126
- const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
127
- const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
128
- let runningInVite = false;
129
- let isProduction = true;
130
- let projectRoot = process.cwd();
131
- let skipFastRefresh = true;
132
- let runPluginOverrides;
133
- let staticBabelOptions;
134
- const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
135
- const viteBabel = {
136
- name: "vite:react-babel",
137
- enforce: "pre",
138
- config() {
139
- if (opts.jsxRuntime === "classic") {
140
- if ("rolldownVersion" in vite) {
141
- return {
142
- oxc: {
143
- jsx: {
144
- runtime: "classic",
145
- // disable __self and __source injection even in dev
146
- // as this plugin injects them by babel and oxc will throw
147
- // if development is enabled and those properties are already present
148
- development: false
149
- }
150
- }
151
- };
152
- } else {
153
- return {
154
- esbuild: {
155
- jsx: "transform"
156
- }
157
- };
158
- }
159
- } else {
160
- return {
161
- esbuild: {
162
- jsx: "automatic",
163
- jsxImportSource: opts.jsxImportSource
164
- },
165
- optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
166
- };
167
- }
168
- },
169
- configResolved(config) {
170
- runningInVite = true;
171
- projectRoot = config.root;
172
- isProduction = config.isProduction;
173
- skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
174
- if ("jsxPure" in opts) {
175
- config.logger.warnOnce(
176
- "[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly."
177
- );
178
- }
179
- const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined);
180
- if ("rolldownVersion" in vite && !opts.babel && !hooks.length && !opts.disableOxcRecommendation) {
181
- config.logger.warn(
182
- "[vite:react-babel] We recommend switching to `@vitejs/plugin-react-oxc` for improved performance. More information at https://vite.dev/rolldown"
183
- );
184
- }
185
- if (hooks.length > 0) {
186
- runPluginOverrides = (babelOptions, context) => {
187
- hooks.forEach((hook) => hook(babelOptions, context, config));
188
- };
189
- } else if (typeof opts.babel !== "function") {
190
- staticBabelOptions = createBabelOptions(opts.babel);
191
- if (canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) && skipFastRefresh && (opts.jsxRuntime === "classic" ? isProduction : true)) {
192
- delete viteBabel.transform;
193
- }
194
- }
195
- },
196
- options(options) {
197
- if (!runningInVite) {
198
- options.jsx = {
199
- mode: opts.jsxRuntime,
200
- importSource: opts.jsxImportSource
201
- };
202
- return options;
203
- }
204
- },
205
- transform: {
206
- filter: {
207
- id: {
208
- include: makeIdFiltersToMatchWithQuery(include),
209
- exclude: [
210
- ...exclude ? makeIdFiltersToMatchWithQuery(ensureArray(exclude)) : [],
211
- /\/node_modules\//
212
- ]
213
- }
214
- },
215
- async handler(code, id, options) {
216
- if (id.includes("/node_modules/")) return;
217
- const [filepath] = id.split("?");
218
- if (!filter(filepath)) return;
219
- const ssr = options?.ssr === true;
220
- const babelOptions = (() => {
221
- if (staticBabelOptions) return staticBabelOptions;
222
- const newBabelOptions = createBabelOptions(
223
- typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
224
- );
225
- runPluginOverrides?.(newBabelOptions, { id, ssr });
226
- return newBabelOptions;
227
- })();
228
- const plugins = [...babelOptions.plugins];
229
- const isJSX = filepath.endsWith("x");
230
- const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
231
- if (useFastRefresh) {
232
- plugins.push([
233
- await loadPlugin("react-refresh/babel"),
234
- { skipEnvCheck: true }
235
- ]);
236
- }
237
- if (opts.jsxRuntime === "classic" && isJSX) {
238
- if (!isProduction) {
239
- plugins.push(
240
- await loadPlugin("@babel/plugin-transform-react-jsx-self"),
241
- await loadPlugin("@babel/plugin-transform-react-jsx-source")
242
- );
243
- }
244
- }
245
- if (canSkipBabel(plugins, babelOptions)) {
246
- return;
247
- }
248
- const parserPlugins = [...babelOptions.parserOpts.plugins];
249
- if (!filepath.endsWith(".ts")) {
250
- parserPlugins.push("jsx");
251
- }
252
- if (tsRE.test(filepath)) {
253
- parserPlugins.push("typescript");
254
- }
255
- const babel2 = await loadBabel();
256
- const result = await babel2.transformAsync(code, {
257
- ...babelOptions,
258
- root: projectRoot,
259
- filename: id,
260
- sourceFileName: filepath,
261
- // Required for esbuild.jsxDev to provide correct line numbers
262
- // This creates issues the react compiler because the re-order is too important
263
- // People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
264
- retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
265
- parserOpts: {
266
- ...babelOptions.parserOpts,
267
- sourceType: "module",
268
- allowAwaitOutsideFunction: true,
269
- plugins: parserPlugins
270
- },
271
- generatorOpts: {
272
- ...babelOptions.generatorOpts,
273
- // import attributes parsing available without plugin since 7.26
274
- importAttributesKeyword: "with",
275
- decoratorsBeforeExport: true
276
- },
277
- plugins,
278
- sourceMaps: true
279
- });
280
- if (result) {
281
- if (!useFastRefresh) {
282
- return { code: result.code, map: result.map };
283
- }
284
- return addRefreshWrapper(
285
- result.code,
286
- result.map,
287
- "@vitejs/plugin-react",
288
- id,
289
- opts.reactRefreshHost
290
- );
291
- }
292
- }
293
- }
294
- };
295
- const dependencies = [
296
- "react",
297
- "react-dom",
298
- jsxImportDevRuntime,
299
- jsxImportRuntime
300
- ];
301
- const staticBabelPlugins = typeof opts.babel === "object" ? opts.babel?.plugins ?? [] : [];
302
- const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
303
- if (reactCompilerPlugin != null) {
304
- const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
305
- dependencies.push(reactCompilerRuntimeModule);
306
- }
307
- const viteReactRefresh = {
308
- name: "vite:react-refresh",
309
- enforce: "pre",
310
- config: (userConfig) => ({
311
- build: silenceUseClientWarning(userConfig),
312
- optimizeDeps: {
313
- include: dependencies
314
- },
315
- resolve: {
316
- dedupe: ["react", "react-dom"]
317
- }
318
- }),
319
- resolveId: {
320
- filter: { id: exactRegex(runtimePublicPath) },
321
- handler(id) {
322
- if (id === runtimePublicPath) {
323
- return id;
324
- }
325
- }
326
- },
327
- load: {
328
- filter: { id: exactRegex(runtimePublicPath) },
329
- handler(id) {
330
- if (id === runtimePublicPath) {
331
- return readFileSync(refreshRuntimePath, "utf-8").replace(
332
- /__README_URL__/g,
333
- "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react"
334
- );
335
- }
336
- }
337
- },
338
- transformIndexHtml(_, config) {
339
- if (!skipFastRefresh)
340
- return [
341
- {
342
- tag: "script",
343
- attrs: { type: "module" },
344
- children: getPreambleCode(config.server.config.base)
345
- }
346
- ];
347
- }
348
- };
349
- return [viteBabel, viteReactRefresh];
350
- }
351
- viteReact.preambleCode = preambleCode;
352
- function canSkipBabel(plugins, babelOptions) {
353
- return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
354
- }
355
- const loadedPlugin = /* @__PURE__ */ new Map();
356
- function loadPlugin(path) {
357
- const cached = loadedPlugin.get(path);
358
- if (cached) return cached;
359
- const promise = import(path).then((module) => {
360
- const value = module.default || module;
361
- loadedPlugin.set(path, value);
362
- return value;
363
- });
364
- loadedPlugin.set(path, promise);
365
- return promise;
366
- }
367
- function createBabelOptions(rawOptions) {
368
- const babelOptions = {
369
- babelrc: false,
370
- configFile: false,
371
- ...rawOptions
372
- };
373
- babelOptions.plugins ||= [];
374
- babelOptions.presets ||= [];
375
- babelOptions.overrides ||= [];
376
- babelOptions.parserOpts ||= {};
377
- babelOptions.parserOpts.plugins ||= [];
378
- return babelOptions;
379
- }
380
- function defined(value) {
381
- return value !== void 0;
382
- }
383
- function getReactCompilerPlugin(plugins) {
384
- return plugins.find(
385
- (p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler"
386
- );
387
- }
388
- function getReactCompilerRuntimeModule(plugin) {
389
- let moduleName = "react/compiler-runtime";
390
- if (Array.isArray(plugin)) {
391
- if (plugin[1]?.target === "17" || plugin[1]?.target === "18") {
392
- moduleName = "react-compiler-runtime";
393
- } else if (typeof plugin[1]?.runtimeModule === "string") {
394
- moduleName = plugin[1]?.runtimeModule;
395
- }
396
- }
397
- return moduleName;
398
- }
399
- function ensureArray(value) {
400
- return Array.isArray(value) ? value : [value];
401
- }
402
-
403
- export { viteReact as default };