1 | import { createFilter } from 'vite';
|
---|
2 | import fs from 'node:fs';
|
---|
3 | import path from 'node:path';
|
---|
4 | import { createRequire } from 'node:module';
|
---|
5 |
|
---|
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;
|
---|
35 | let prevRefreshSig;
|
---|
36 |
|
---|
37 | if (import.meta.hot && !inWebWorker) {
|
---|
38 | if (!window.__vite_plugin_react_preamble_installed__) {
|
---|
39 | 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"
|
---|
42 | );
|
---|
43 | }
|
---|
44 |
|
---|
45 | prevRefreshReg = window.$RefreshReg$;
|
---|
46 | prevRefreshSig = window.$RefreshSig$;
|
---|
47 | window.$RefreshReg$ = (type, id) => {
|
---|
48 | RefreshRuntime.register(type, __SOURCE__ + " " + id)
|
---|
49 | };
|
---|
50 | window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
|
---|
51 | }`.replace(/\n+/g, "");
|
---|
52 | const functionFooter = `
|
---|
53 | if (import.meta.hot && !inWebWorker) {
|
---|
54 | window.$RefreshReg$ = prevRefreshReg;
|
---|
55 | window.$RefreshSig$ = prevRefreshSig;
|
---|
56 | }`;
|
---|
57 | const sharedFooter = `
|
---|
58 | if (import.meta.hot && !inWebWorker) {
|
---|
59 | RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
|
---|
60 | RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
|
---|
61 | import.meta.hot.accept((nextExports) => {
|
---|
62 | if (!nextExports) return;
|
---|
63 | const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports);
|
---|
64 | if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
|
---|
65 | });
|
---|
66 | });
|
---|
67 | }`;
|
---|
68 | function addRefreshWrapper(code, id) {
|
---|
69 | return sharedHeader + functionHeader.replace("__SOURCE__", JSON.stringify(id)) + code + functionFooter + sharedFooter.replace("__SOURCE__", JSON.stringify(id));
|
---|
70 | }
|
---|
71 | function addClassComponentRefreshWrapper(code, id) {
|
---|
72 | return sharedHeader + code + sharedFooter.replace("__SOURCE__", JSON.stringify(id));
|
---|
73 | }
|
---|
74 |
|
---|
75 | let babel;
|
---|
76 | async function loadBabel() {
|
---|
77 | if (!babel) {
|
---|
78 | babel = await import('@babel/core');
|
---|
79 | }
|
---|
80 | return babel;
|
---|
81 | }
|
---|
82 | const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
|
---|
83 | const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
|
---|
84 | const defaultIncludeRE = /\.[tj]sx?$/;
|
---|
85 | const tsRE = /\.tsx?$/;
|
---|
86 | function viteReact(opts = {}) {
|
---|
87 | let devBase = "/";
|
---|
88 | const filter = createFilter(opts.include ?? defaultIncludeRE, opts.exclude);
|
---|
89 | const jsxImportSource = opts.jsxImportSource ?? "react";
|
---|
90 | const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
|
---|
91 | const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
|
---|
92 | let isProduction = true;
|
---|
93 | let projectRoot = process.cwd();
|
---|
94 | let skipFastRefresh = false;
|
---|
95 | let runPluginOverrides;
|
---|
96 | let staticBabelOptions;
|
---|
97 | const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
|
---|
98 | const viteBabel = {
|
---|
99 | name: "vite:react-babel",
|
---|
100 | enforce: "pre",
|
---|
101 | config() {
|
---|
102 | if (opts.jsxRuntime === "classic") {
|
---|
103 | return {
|
---|
104 | esbuild: {
|
---|
105 | jsx: "transform"
|
---|
106 | }
|
---|
107 | };
|
---|
108 | } else {
|
---|
109 | return {
|
---|
110 | esbuild: {
|
---|
111 | jsx: "automatic",
|
---|
112 | jsxImportSource: opts.jsxImportSource
|
---|
113 | },
|
---|
114 | optimizeDeps: { esbuildOptions: { jsx: "automatic" } }
|
---|
115 | };
|
---|
116 | }
|
---|
117 | },
|
---|
118 | configResolved(config) {
|
---|
119 | devBase = config.base;
|
---|
120 | projectRoot = config.root;
|
---|
121 | isProduction = config.isProduction;
|
---|
122 | skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
|
---|
123 | if ("jsxPure" in opts) {
|
---|
124 | config.logger.warnOnce(
|
---|
125 | "[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly."
|
---|
126 | );
|
---|
127 | }
|
---|
128 | const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined);
|
---|
129 | if (hooks.length > 0) {
|
---|
130 | runPluginOverrides = (babelOptions, context) => {
|
---|
131 | hooks.forEach((hook) => hook(babelOptions, context, config));
|
---|
132 | };
|
---|
133 | } else if (typeof opts.babel !== "function") {
|
---|
134 | staticBabelOptions = createBabelOptions(opts.babel);
|
---|
135 | }
|
---|
136 | },
|
---|
137 | async transform(code, id, options) {
|
---|
138 | if (id.includes("/node_modules/"))
|
---|
139 | return;
|
---|
140 | const [filepath] = id.split("?");
|
---|
141 | if (!filter(filepath))
|
---|
142 | return;
|
---|
143 | const ssr = options?.ssr === true;
|
---|
144 | const babelOptions = (() => {
|
---|
145 | if (staticBabelOptions)
|
---|
146 | return staticBabelOptions;
|
---|
147 | const newBabelOptions = createBabelOptions(
|
---|
148 | typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
|
---|
149 | );
|
---|
150 | runPluginOverrides?.(newBabelOptions, { id, ssr });
|
---|
151 | return newBabelOptions;
|
---|
152 | })();
|
---|
153 | const plugins = [...babelOptions.plugins];
|
---|
154 | const isJSX = filepath.endsWith("x");
|
---|
155 | const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
|
---|
156 | if (useFastRefresh) {
|
---|
157 | plugins.push([
|
---|
158 | await loadPlugin("react-refresh/babel"),
|
---|
159 | { skipEnvCheck: true }
|
---|
160 | ]);
|
---|
161 | }
|
---|
162 | if (opts.jsxRuntime === "classic" && isJSX) {
|
---|
163 | if (!isProduction) {
|
---|
164 | plugins.push(
|
---|
165 | await loadPlugin("@babel/plugin-transform-react-jsx-self"),
|
---|
166 | await loadPlugin("@babel/plugin-transform-react-jsx-source")
|
---|
167 | );
|
---|
168 | }
|
---|
169 | }
|
---|
170 | if (!plugins.length && !babelOptions.presets.length && !babelOptions.configFile && !babelOptions.babelrc) {
|
---|
171 | return;
|
---|
172 | }
|
---|
173 | const parserPlugins = [...babelOptions.parserOpts.plugins];
|
---|
174 | if (!filepath.endsWith(".ts")) {
|
---|
175 | parserPlugins.push("jsx");
|
---|
176 | }
|
---|
177 | if (tsRE.test(filepath)) {
|
---|
178 | parserPlugins.push("typescript");
|
---|
179 | }
|
---|
180 | const babel2 = await loadBabel();
|
---|
181 | const result = await babel2.transformAsync(code, {
|
---|
182 | ...babelOptions,
|
---|
183 | root: projectRoot,
|
---|
184 | filename: id,
|
---|
185 | sourceFileName: filepath,
|
---|
186 | // Required for esbuild.jsxDev to provide correct line numbers
|
---|
187 | // This crates issues the react compiler because the re-order is too important
|
---|
188 | // People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
|
---|
189 | retainLines: hasCompiler(plugins) ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
|
---|
190 | parserOpts: {
|
---|
191 | ...babelOptions.parserOpts,
|
---|
192 | sourceType: "module",
|
---|
193 | allowAwaitOutsideFunction: true,
|
---|
194 | plugins: parserPlugins
|
---|
195 | },
|
---|
196 | generatorOpts: {
|
---|
197 | ...babelOptions.generatorOpts,
|
---|
198 | decoratorsBeforeExport: true
|
---|
199 | },
|
---|
200 | plugins,
|
---|
201 | sourceMaps: true
|
---|
202 | });
|
---|
203 | if (result) {
|
---|
204 | let code2 = result.code;
|
---|
205 | if (useFastRefresh) {
|
---|
206 | if (refreshContentRE.test(code2)) {
|
---|
207 | code2 = addRefreshWrapper(code2, id);
|
---|
208 | } else if (reactCompRE.test(code2)) {
|
---|
209 | code2 = addClassComponentRefreshWrapper(code2, id);
|
---|
210 | }
|
---|
211 | }
|
---|
212 | return { code: code2, map: result.map };
|
---|
213 | }
|
---|
214 | }
|
---|
215 | };
|
---|
216 | const dependencies = ["react", jsxImportDevRuntime, jsxImportRuntime];
|
---|
217 | const staticBabelPlugins = typeof opts.babel === "object" ? opts.babel?.plugins ?? [] : [];
|
---|
218 | if (hasCompilerWithDefaultRuntime(staticBabelPlugins)) {
|
---|
219 | dependencies.push("react/compiler-runtime");
|
---|
220 | }
|
---|
221 | const viteReactRefresh = {
|
---|
222 | name: "vite:react-refresh",
|
---|
223 | enforce: "pre",
|
---|
224 | config: (userConfig) => ({
|
---|
225 | build: silenceUseClientWarning(userConfig),
|
---|
226 | optimizeDeps: {
|
---|
227 | include: dependencies
|
---|
228 | },
|
---|
229 | resolve: {
|
---|
230 | dedupe: ["react", "react-dom"]
|
---|
231 | }
|
---|
232 | }),
|
---|
233 | resolveId(id) {
|
---|
234 | if (id === runtimePublicPath) {
|
---|
235 | return id;
|
---|
236 | }
|
---|
237 | },
|
---|
238 | load(id) {
|
---|
239 | if (id === runtimePublicPath) {
|
---|
240 | return runtimeCode;
|
---|
241 | }
|
---|
242 | },
|
---|
243 | transformIndexHtml() {
|
---|
244 | if (!skipFastRefresh)
|
---|
245 | return [
|
---|
246 | {
|
---|
247 | tag: "script",
|
---|
248 | attrs: { type: "module" },
|
---|
249 | children: preambleCode.replace(`__BASE__`, devBase)
|
---|
250 | }
|
---|
251 | ];
|
---|
252 | }
|
---|
253 | };
|
---|
254 | return [viteBabel, viteReactRefresh];
|
---|
255 | }
|
---|
256 | viteReact.preambleCode = preambleCode;
|
---|
257 | const silenceUseClientWarning = (userConfig) => ({
|
---|
258 | rollupOptions: {
|
---|
259 | onwarn(warning, defaultHandler) {
|
---|
260 | if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
|
---|
261 | return;
|
---|
262 | }
|
---|
263 | if (userConfig.build?.rollupOptions?.onwarn) {
|
---|
264 | userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
|
---|
265 | } else {
|
---|
266 | defaultHandler(warning);
|
---|
267 | }
|
---|
268 | }
|
---|
269 | }
|
---|
270 | });
|
---|
271 | const loadedPlugin = /* @__PURE__ */ new Map();
|
---|
272 | function loadPlugin(path) {
|
---|
273 | const cached = loadedPlugin.get(path);
|
---|
274 | if (cached)
|
---|
275 | return cached;
|
---|
276 | const promise = import(path).then((module) => {
|
---|
277 | const value = module.default || module;
|
---|
278 | loadedPlugin.set(path, value);
|
---|
279 | return value;
|
---|
280 | });
|
---|
281 | loadedPlugin.set(path, promise);
|
---|
282 | return promise;
|
---|
283 | }
|
---|
284 | function createBabelOptions(rawOptions) {
|
---|
285 | var _a;
|
---|
286 | const babelOptions = {
|
---|
287 | babelrc: false,
|
---|
288 | configFile: false,
|
---|
289 | ...rawOptions
|
---|
290 | };
|
---|
291 | babelOptions.plugins || (babelOptions.plugins = []);
|
---|
292 | babelOptions.presets || (babelOptions.presets = []);
|
---|
293 | babelOptions.overrides || (babelOptions.overrides = []);
|
---|
294 | babelOptions.parserOpts || (babelOptions.parserOpts = {});
|
---|
295 | (_a = babelOptions.parserOpts).plugins || (_a.plugins = []);
|
---|
296 | return babelOptions;
|
---|
297 | }
|
---|
298 | function defined(value) {
|
---|
299 | return value !== void 0;
|
---|
300 | }
|
---|
301 | function hasCompiler(plugins) {
|
---|
302 | return plugins.some(
|
---|
303 | (p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler"
|
---|
304 | );
|
---|
305 | }
|
---|
306 | function hasCompilerWithDefaultRuntime(plugins) {
|
---|
307 | return plugins.some(
|
---|
308 | (p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler" && p[1]?.runtimeModule === void 0
|
---|
309 | );
|
---|
310 | }
|
---|
311 |
|
---|
312 | export { viteReact as default };
|
---|