index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 { exactRegex, makeIdFiltersToMatchWithQuery } from "@rolldown/pluginutils";
  7. //#region ../common/refresh-utils.ts
  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(1)}";
  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 {
  22. code,
  23. map: normalizedMap
  24. };
  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(`let prevRefreshReg;
  30. let prevRefreshSig;
  31. if (import.meta.hot && !inWebWorker) {
  32. if (!window.$RefreshReg$) {
  33. throw new Error(
  34. "${pluginName} can't detect preamble. Something is wrong."
  35. );
  36. }
  37. prevRefreshReg = window.$RefreshReg$;
  38. prevRefreshSig = window.$RefreshSig$;
  39. window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
  40. window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
  41. }
  42. `, avoidSourceMap);
  43. newCode = `${refreshHead}${newCode}
  44. if (import.meta.hot && !inWebWorker) {
  45. window.$RefreshReg$ = prevRefreshReg;
  46. window.$RefreshSig$ = prevRefreshSig;
  47. }
  48. `;
  49. if (newMap) newMap.mappings = ";".repeat(16) + newMap.mappings;
  50. }
  51. const sharedHead = removeLineBreaksIfNeeded(`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
  52. const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
  53. `, avoidSourceMap);
  54. newCode = `${sharedHead}${newCode}
  55. if (import.meta.hot && !inWebWorker) {
  56. RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
  57. RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(id)}, currentExports);
  58. import.meta.hot.accept((nextExports) => {
  59. if (!nextExports) return;
  60. const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(id)}, currentExports, nextExports);
  61. if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
  62. });
  63. });
  64. }
  65. `;
  66. if (newMap) newMap.mappings = ";;;" + newMap.mappings;
  67. return {
  68. code: newCode,
  69. map: newMap
  70. };
  71. }
  72. function removeLineBreaksIfNeeded(code, enabled) {
  73. return enabled ? code.replace(/\n/g, "") : code;
  74. }
  75. //#endregion
  76. //#region ../common/warning.ts
  77. const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
  78. var _userConfig$build;
  79. if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
  80. if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
  81. if ((_userConfig$build = userConfig.build) === null || _userConfig$build === void 0 || (_userConfig$build = _userConfig$build.rollupOptions) === null || _userConfig$build === void 0 ? void 0 : _userConfig$build.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
  82. else defaultHandler(warning);
  83. } } });
  84. //#endregion
  85. //#region src/index.ts
  86. const _dirname = dirname(fileURLToPath(import.meta.url));
  87. const refreshRuntimePath = join(_dirname, "refresh-runtime.js");
  88. let babel;
  89. async function loadBabel() {
  90. if (!babel) babel = await import("@babel/core");
  91. return babel;
  92. }
  93. const defaultIncludeRE = /\.[tj]sx?$/;
  94. const tsRE = /\.tsx?$/;
  95. function viteReact(opts = {}) {
  96. var _opts$babel;
  97. const include = opts.include ?? defaultIncludeRE;
  98. const exclude = opts.exclude;
  99. const filter = createFilter(include, exclude);
  100. const jsxImportSource = opts.jsxImportSource ?? "react";
  101. const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
  102. const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
  103. let runningInVite = false;
  104. let isProduction = true;
  105. let projectRoot = process.cwd();
  106. let skipFastRefresh = true;
  107. let runPluginOverrides;
  108. let staticBabelOptions;
  109. const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
  110. const viteBabel = {
  111. name: "vite:react-babel",
  112. enforce: "pre",
  113. config() {
  114. if (opts.jsxRuntime === "classic") if ("rolldownVersion" in vite) return { oxc: { jsx: {
  115. runtime: "classic",
  116. development: false
  117. } } };
  118. else return { esbuild: { jsx: "transform" } };
  119. else return {
  120. esbuild: {
  121. jsx: "automatic",
  122. jsxImportSource: opts.jsxImportSource
  123. },
  124. optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
  125. };
  126. },
  127. configResolved(config) {
  128. runningInVite = true;
  129. projectRoot = config.root;
  130. isProduction = config.isProduction;
  131. skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
  132. if ("jsxPure" in opts) config.logger.warnOnce("[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly.");
  133. const hooks = config.plugins.map((plugin) => {
  134. var _plugin$api;
  135. return (_plugin$api = plugin.api) === null || _plugin$api === void 0 ? void 0 : _plugin$api.reactBabel;
  136. }).filter(defined);
  137. if ("rolldownVersion" in vite && !opts.babel && !hooks.length && !opts.disableOxcRecommendation) config.logger.warn("[vite:react-babel] We recommend switching to `@vitejs/plugin-react-oxc` for improved performance. More information at https://vite.dev/rolldown");
  138. if (hooks.length > 0) runPluginOverrides = (babelOptions, context) => {
  139. hooks.forEach((hook) => hook(babelOptions, context, config));
  140. };
  141. else if (typeof opts.babel !== "function") {
  142. staticBabelOptions = createBabelOptions(opts.babel);
  143. if (canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) && skipFastRefresh && (opts.jsxRuntime === "classic" ? isProduction : true)) delete viteBabel.transform;
  144. }
  145. },
  146. options(options) {
  147. if (!runningInVite) {
  148. options.jsx = {
  149. mode: opts.jsxRuntime,
  150. importSource: opts.jsxImportSource
  151. };
  152. return options;
  153. }
  154. },
  155. transform: {
  156. filter: { id: {
  157. include: makeIdFiltersToMatchWithQuery(include),
  158. exclude: [...exclude ? makeIdFiltersToMatchWithQuery(ensureArray(exclude)) : [], /\/node_modules\//]
  159. } },
  160. async handler(code, id, options) {
  161. if (id.includes("/node_modules/")) return;
  162. const [filepath] = id.split("?");
  163. if (!filter(filepath)) return;
  164. const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
  165. const babelOptions = (() => {
  166. if (staticBabelOptions) return staticBabelOptions;
  167. const newBabelOptions = createBabelOptions(typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel);
  168. runPluginOverrides === null || runPluginOverrides === void 0 || runPluginOverrides(newBabelOptions, {
  169. id,
  170. ssr
  171. });
  172. return newBabelOptions;
  173. })();
  174. const plugins = [...babelOptions.plugins];
  175. const isJSX = filepath.endsWith("x");
  176. const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
  177. if (useFastRefresh) plugins.push([await loadPlugin("react-refresh/babel"), { skipEnvCheck: true }]);
  178. if (opts.jsxRuntime === "classic" && isJSX) {
  179. if (!isProduction) plugins.push(await loadPlugin("@babel/plugin-transform-react-jsx-self"), await loadPlugin("@babel/plugin-transform-react-jsx-source"));
  180. }
  181. if (canSkipBabel(plugins, babelOptions)) return;
  182. const parserPlugins = [...babelOptions.parserOpts.plugins];
  183. if (!filepath.endsWith(".ts")) parserPlugins.push("jsx");
  184. if (tsRE.test(filepath)) parserPlugins.push("typescript");
  185. const babel$1 = await loadBabel();
  186. const result = await babel$1.transformAsync(code, {
  187. ...babelOptions,
  188. root: projectRoot,
  189. filename: id,
  190. sourceFileName: filepath,
  191. retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
  192. parserOpts: {
  193. ...babelOptions.parserOpts,
  194. sourceType: "module",
  195. allowAwaitOutsideFunction: true,
  196. plugins: parserPlugins
  197. },
  198. generatorOpts: {
  199. ...babelOptions.generatorOpts,
  200. importAttributesKeyword: "with",
  201. decoratorsBeforeExport: true
  202. },
  203. plugins,
  204. sourceMaps: true
  205. });
  206. if (result) {
  207. if (!useFastRefresh) return {
  208. code: result.code,
  209. map: result.map
  210. };
  211. return addRefreshWrapper(result.code, result.map, "@vitejs/plugin-react", id, opts.reactRefreshHost);
  212. }
  213. }
  214. }
  215. };
  216. const dependencies = [
  217. "react",
  218. "react-dom",
  219. jsxImportDevRuntime,
  220. jsxImportRuntime
  221. ];
  222. const staticBabelPlugins = typeof opts.babel === "object" ? ((_opts$babel = opts.babel) === null || _opts$babel === void 0 ? void 0 : _opts$babel.plugins) ?? [] : [];
  223. const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
  224. if (reactCompilerPlugin != null) {
  225. const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
  226. dependencies.push(reactCompilerRuntimeModule);
  227. }
  228. const viteReactRefresh = {
  229. name: "vite:react-refresh",
  230. enforce: "pre",
  231. config: (userConfig) => ({
  232. build: silenceUseClientWarning(userConfig),
  233. optimizeDeps: { include: dependencies },
  234. resolve: { dedupe: ["react", "react-dom"] }
  235. }),
  236. resolveId: {
  237. filter: { id: exactRegex(runtimePublicPath) },
  238. handler(id) {
  239. if (id === runtimePublicPath) return id;
  240. }
  241. },
  242. load: {
  243. filter: { id: exactRegex(runtimePublicPath) },
  244. handler(id) {
  245. if (id === runtimePublicPath) return readFileSync(refreshRuntimePath, "utf-8").replace(/__README_URL__/g, "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react");
  246. }
  247. },
  248. transformIndexHtml(_, config) {
  249. if (!skipFastRefresh) return [{
  250. tag: "script",
  251. attrs: { type: "module" },
  252. children: getPreambleCode(config.server.config.base)
  253. }];
  254. }
  255. };
  256. return [viteBabel, viteReactRefresh];
  257. }
  258. viteReact.preambleCode = preambleCode;
  259. function canSkipBabel(plugins, babelOptions) {
  260. return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
  261. }
  262. const loadedPlugin = /* @__PURE__ */ new Map();
  263. function loadPlugin(path) {
  264. const cached = loadedPlugin.get(path);
  265. if (cached) return cached;
  266. const promise = import(path).then((module) => {
  267. const value = module.default || module;
  268. loadedPlugin.set(path, value);
  269. return value;
  270. });
  271. loadedPlugin.set(path, promise);
  272. return promise;
  273. }
  274. function createBabelOptions(rawOptions) {
  275. var _babelOptions$parserO;
  276. const babelOptions = {
  277. babelrc: false,
  278. configFile: false,
  279. ...rawOptions
  280. };
  281. babelOptions.plugins || (babelOptions.plugins = []);
  282. babelOptions.presets || (babelOptions.presets = []);
  283. babelOptions.overrides || (babelOptions.overrides = []);
  284. babelOptions.parserOpts || (babelOptions.parserOpts = {});
  285. (_babelOptions$parserO = babelOptions.parserOpts).plugins || (_babelOptions$parserO.plugins = []);
  286. return babelOptions;
  287. }
  288. function defined(value) {
  289. return value !== void 0;
  290. }
  291. function getReactCompilerPlugin(plugins) {
  292. return plugins.find((p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler");
  293. }
  294. function getReactCompilerRuntimeModule(plugin) {
  295. let moduleName = "react/compiler-runtime";
  296. if (Array.isArray(plugin)) {
  297. var _plugin$, _plugin$2, _plugin$3;
  298. if (((_plugin$ = plugin[1]) === null || _plugin$ === void 0 ? void 0 : _plugin$.target) === "17" || ((_plugin$2 = plugin[1]) === null || _plugin$2 === void 0 ? void 0 : _plugin$2.target) === "18") moduleName = "react-compiler-runtime";
  299. else if (typeof ((_plugin$3 = plugin[1]) === null || _plugin$3 === void 0 ? void 0 : _plugin$3.runtimeModule) === "string") {
  300. var _plugin$4;
  301. moduleName = (_plugin$4 = plugin[1]) === null || _plugin$4 === void 0 ? void 0 : _plugin$4.runtimeModule;
  302. }
  303. }
  304. return moduleName;
  305. }
  306. function ensureArray(value) {
  307. return Array.isArray(value) ? value : [value];
  308. }
  309. //#endregion
  310. export { viteReact as default };