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