source: imaps-frontend/node_modules/@vitejs/plugin-react/dist/index.mjs@ 0c6b92a

main
Last change on this file since 0c6b92a was 0c6b92a, checked in by stefan toskovski <stefantoska84@…>, 5 weeks ago

Pred finalna verzija

  • Property mode set to 100644
File size: 10.9 KB
RevLine 
[d565449]1import { createFilter } from 'vite';
2import fs from 'node:fs';
3import path from 'node:path';
4import { createRequire } from 'node:module';
5
6const runtimePublicPath = "/@react-refresh";
7const _require = createRequire(import.meta.url);
8const reactRefreshDir = path.dirname(
9 _require.resolve("react-refresh/package.json")
10);
11const runtimeFilePath = path.join(
12 reactRefreshDir,
13 "cjs/react-refresh-runtime.development.js"
14);
15const runtimeCode = `
16const exports = {}
17${fs.readFileSync(runtimeFilePath, "utf-8")}
18${fs.readFileSync(_require.resolve("./refreshUtils.js"), "utf-8")}
19export default exports
20`;
21const preambleCode = `
22import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}"
23RefreshRuntime.injectIntoGlobalHook(window)
24window.$RefreshReg$ = () => {}
25window.$RefreshSig$ = () => (type) => type
26window.__vite_plugin_react_preamble_installed__ = true
27`;
28const sharedHeader = `
29import RefreshRuntime from "${runtimePublicPath}";
30
31const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
32`.replace(/\n+/g, "");
33const functionHeader = `
34let prevRefreshReg;
35let prevRefreshSig;
36
37if (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, "");
52const functionFooter = `
53if (import.meta.hot && !inWebWorker) {
54 window.$RefreshReg$ = prevRefreshReg;
55 window.$RefreshSig$ = prevRefreshSig;
56}`;
[0c6b92a]57const sharedFooter = (id) => `
[d565449]58if (import.meta.hot && !inWebWorker) {
59 RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
[0c6b92a]60 RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
61 id
62)}, currentExports);
[d565449]63 import.meta.hot.accept((nextExports) => {
64 if (!nextExports) return;
[0c6b92a]65 const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
66 id
67)}, currentExports, nextExports);
[d565449]68 if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
69 });
70 });
71}`;
72function addRefreshWrapper(code, id) {
[0c6b92a]73 return sharedHeader + functionHeader.replace("__SOURCE__", JSON.stringify(id)) + code + functionFooter + sharedFooter(id);
[d565449]74}
75function addClassComponentRefreshWrapper(code, id) {
[0c6b92a]76 return sharedHeader + code + sharedFooter(id);
[d565449]77}
78
79let babel;
80async function loadBabel() {
81 if (!babel) {
82 babel = await import('@babel/core');
83 }
84 return babel;
85}
86const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
87const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
88const defaultIncludeRE = /\.[tj]sx?$/;
89const tsRE = /\.tsx?$/;
90function viteReact(opts = {}) {
91 let devBase = "/";
92 const filter = createFilter(opts.include ?? defaultIncludeRE, opts.exclude);
93 const jsxImportSource = opts.jsxImportSource ?? "react";
94 const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
95 const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
96 let isProduction = true;
97 let projectRoot = process.cwd();
98 let skipFastRefresh = false;
99 let runPluginOverrides;
100 let staticBabelOptions;
101 const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
102 const viteBabel = {
103 name: "vite:react-babel",
104 enforce: "pre",
105 config() {
106 if (opts.jsxRuntime === "classic") {
107 return {
108 esbuild: {
109 jsx: "transform"
110 }
111 };
112 } else {
113 return {
114 esbuild: {
115 jsx: "automatic",
116 jsxImportSource: opts.jsxImportSource
117 },
118 optimizeDeps: { esbuildOptions: { jsx: "automatic" } }
119 };
120 }
121 },
122 configResolved(config) {
123 devBase = config.base;
124 projectRoot = config.root;
125 isProduction = config.isProduction;
126 skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
127 if ("jsxPure" in opts) {
128 config.logger.warnOnce(
129 "[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly."
130 );
131 }
132 const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined);
133 if (hooks.length > 0) {
134 runPluginOverrides = (babelOptions, context) => {
135 hooks.forEach((hook) => hook(babelOptions, context, config));
136 };
137 } else if (typeof opts.babel !== "function") {
138 staticBabelOptions = createBabelOptions(opts.babel);
139 }
140 },
141 async transform(code, id, options) {
142 if (id.includes("/node_modules/"))
143 return;
144 const [filepath] = id.split("?");
145 if (!filter(filepath))
146 return;
147 const ssr = options?.ssr === true;
148 const babelOptions = (() => {
149 if (staticBabelOptions)
150 return staticBabelOptions;
151 const newBabelOptions = createBabelOptions(
152 typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
153 );
154 runPluginOverrides?.(newBabelOptions, { id, ssr });
155 return newBabelOptions;
156 })();
157 const plugins = [...babelOptions.plugins];
158 const isJSX = filepath.endsWith("x");
159 const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
160 if (useFastRefresh) {
161 plugins.push([
162 await loadPlugin("react-refresh/babel"),
163 { skipEnvCheck: true }
164 ]);
165 }
166 if (opts.jsxRuntime === "classic" && isJSX) {
167 if (!isProduction) {
168 plugins.push(
169 await loadPlugin("@babel/plugin-transform-react-jsx-self"),
170 await loadPlugin("@babel/plugin-transform-react-jsx-source")
171 );
172 }
173 }
174 if (!plugins.length && !babelOptions.presets.length && !babelOptions.configFile && !babelOptions.babelrc) {
175 return;
176 }
177 const parserPlugins = [...babelOptions.parserOpts.plugins];
178 if (!filepath.endsWith(".ts")) {
179 parserPlugins.push("jsx");
180 }
181 if (tsRE.test(filepath)) {
182 parserPlugins.push("typescript");
183 }
184 const babel2 = await loadBabel();
185 const result = await babel2.transformAsync(code, {
186 ...babelOptions,
187 root: projectRoot,
188 filename: id,
189 sourceFileName: filepath,
190 // Required for esbuild.jsxDev to provide correct line numbers
191 // This crates issues the react compiler because the re-order is too important
192 // People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
[0c6b92a]193 retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
[d565449]194 parserOpts: {
195 ...babelOptions.parserOpts,
196 sourceType: "module",
197 allowAwaitOutsideFunction: true,
198 plugins: parserPlugins
199 },
200 generatorOpts: {
201 ...babelOptions.generatorOpts,
[0c6b92a]202 // import attributes parsing available without plugin since 7.26
203 importAttributesKeyword: "with",
[d565449]204 decoratorsBeforeExport: true
205 },
206 plugins,
207 sourceMaps: true
208 });
209 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 }
217 }
218 return { code: code2, map: result.map };
219 }
220 }
221 };
[0c6b92a]222 const dependencies = [
223 "react",
224 "react-dom",
225 jsxImportDevRuntime,
226 jsxImportRuntime
227 ];
[d565449]228 const staticBabelPlugins = typeof opts.babel === "object" ? opts.babel?.plugins ?? [] : [];
[0c6b92a]229 const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
230 if (reactCompilerPlugin != null) {
231 const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
232 dependencies.push(reactCompilerRuntimeModule);
[d565449]233 }
234 const viteReactRefresh = {
235 name: "vite:react-refresh",
236 enforce: "pre",
237 config: (userConfig) => ({
238 build: silenceUseClientWarning(userConfig),
239 optimizeDeps: {
240 include: dependencies
241 },
242 resolve: {
243 dedupe: ["react", "react-dom"]
244 }
245 }),
246 resolveId(id) {
247 if (id === runtimePublicPath) {
248 return id;
249 }
250 },
251 load(id) {
252 if (id === runtimePublicPath) {
253 return runtimeCode;
254 }
255 },
256 transformIndexHtml() {
257 if (!skipFastRefresh)
258 return [
259 {
260 tag: "script",
261 attrs: { type: "module" },
262 children: preambleCode.replace(`__BASE__`, devBase)
263 }
264 ];
265 }
266 };
267 return [viteBabel, viteReactRefresh];
268}
269viteReact.preambleCode = preambleCode;
270const silenceUseClientWarning = (userConfig) => ({
271 rollupOptions: {
272 onwarn(warning, defaultHandler) {
273 if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
274 return;
275 }
[0c6b92a]276 if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
277 return;
278 }
[d565449]279 if (userConfig.build?.rollupOptions?.onwarn) {
280 userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
281 } else {
282 defaultHandler(warning);
283 }
284 }
285 }
286});
287const loadedPlugin = /* @__PURE__ */ new Map();
288function loadPlugin(path) {
289 const cached = loadedPlugin.get(path);
290 if (cached)
291 return cached;
292 const promise = import(path).then((module) => {
293 const value = module.default || module;
294 loadedPlugin.set(path, value);
295 return value;
296 });
297 loadedPlugin.set(path, promise);
298 return promise;
299}
300function createBabelOptions(rawOptions) {
301 var _a;
302 const babelOptions = {
303 babelrc: false,
304 configFile: false,
305 ...rawOptions
306 };
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 = []);
312 return babelOptions;
313}
314function defined(value) {
315 return value !== void 0;
316}
[0c6b92a]317function getReactCompilerPlugin(plugins) {
318 return plugins.find(
[d565449]319 (p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler"
320 );
321}
[0c6b92a]322function getReactCompilerRuntimeModule(plugin) {
323 let moduleName = "react/compiler-runtime";
324 if (Array.isArray(plugin)) {
325 if (plugin[1]?.target === "17" || plugin[1]?.target === "18") {
326 moduleName = "react-compiler-runtime";
327 } else if (typeof plugin[1]?.runtimeModule === "string") {
328 moduleName = plugin[1]?.runtimeModule;
329 }
330 }
331 return moduleName;
[d565449]332}
333
334export { viteReact as default };
Note: See TracBrowser for help on using the repository browser.