@vitejs/plugin-react-swc 3.10.2 → 3.11.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/index.mjs DELETED
@@ -1,293 +0,0 @@
1
- // src/index.ts
2
- import { readFileSync } from "fs";
3
- import { dirname, join } from "path";
4
- import { fileURLToPath } from "url";
5
- import { createRequire } from "module";
6
- import {
7
- transform
8
- } from "@swc/core";
9
-
10
- // ../common/refresh-utils.ts
11
- var runtimePublicPath = "/@react-refresh";
12
- var reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
13
- var refreshContentRE = /\$RefreshReg\$\(/;
14
- var preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
15
- 1
16
- )}";
17
- injectIntoGlobalHook(window);
18
- window.$RefreshReg$ = () => {};
19
- window.$RefreshSig$ = () => (type) => type;`;
20
- var getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
21
- var avoidSourceMapOption = Symbol();
22
- function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
23
- const hasRefresh = refreshContentRE.test(code);
24
- const onlyReactComp = !hasRefresh && reactCompRE.test(code);
25
- const normalizedMap = map === avoidSourceMapOption ? null : map;
26
- if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
27
- const avoidSourceMap = map === avoidSourceMapOption;
28
- const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
29
- let newCode = code;
30
- if (hasRefresh) {
31
- const refreshHead = removeLineBreaksIfNeeded(
32
- `let prevRefreshReg;
33
- let prevRefreshSig;
34
-
35
- if (import.meta.hot && !inWebWorker) {
36
- if (!window.$RefreshReg$) {
37
- throw new Error(
38
- "${pluginName} can't detect preamble. Something is wrong."
39
- );
40
- }
41
-
42
- prevRefreshReg = window.$RefreshReg$;
43
- prevRefreshSig = window.$RefreshSig$;
44
- window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
45
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
46
- }
47
-
48
- `,
49
- avoidSourceMap
50
- );
51
- newCode = `${refreshHead}${newCode}
52
-
53
- if (import.meta.hot && !inWebWorker) {
54
- window.$RefreshReg$ = prevRefreshReg;
55
- window.$RefreshSig$ = prevRefreshSig;
56
- }
57
- `;
58
- if (newMap) {
59
- newMap.mappings = ";".repeat(16) + newMap.mappings;
60
- }
61
- }
62
- const sharedHead = removeLineBreaksIfNeeded(
63
- `import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
64
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
65
-
66
- `,
67
- avoidSourceMap
68
- );
69
- newCode = `${sharedHead}${newCode}
70
-
71
- if (import.meta.hot && !inWebWorker) {
72
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
73
- RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
74
- id
75
- )}, currentExports);
76
- import.meta.hot.accept((nextExports) => {
77
- if (!nextExports) return;
78
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
79
- id
80
- )}, currentExports, nextExports);
81
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
82
- });
83
- });
84
- }
85
- `;
86
- if (newMap) {
87
- newMap.mappings = ";;;" + newMap.mappings;
88
- }
89
- return { code: newCode, map: newMap };
90
- }
91
- function removeLineBreaksIfNeeded(code, enabled) {
92
- return enabled ? code.replace(/\n/g, "") : code;
93
- }
94
-
95
- // ../common/warning.ts
96
- var silenceUseClientWarning = (userConfig) => ({
97
- rollupOptions: {
98
- onwarn(warning, defaultHandler) {
99
- var _a, _b;
100
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
101
- return;
102
- }
103
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
104
- return;
105
- }
106
- if ((_b = (_a = userConfig.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.onwarn) {
107
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
108
- } else {
109
- defaultHandler(warning);
110
- }
111
- }
112
- }
113
- });
114
-
115
- // src/index.ts
116
- import * as vite from "vite";
117
- import { exactRegex } from "@rolldown/pluginutils";
118
- var _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
119
- var resolve = createRequire(
120
- typeof __filename !== "undefined" ? __filename : import.meta.url
121
- ).resolve;
122
- var react = (_options) => {
123
- let hmrDisabled = false;
124
- const options = {
125
- jsxImportSource: (_options == null ? void 0 : _options.jsxImportSource) ?? "react",
126
- tsDecorators: _options == null ? void 0 : _options.tsDecorators,
127
- plugins: (_options == null ? void 0 : _options.plugins) ? _options == null ? void 0 : _options.plugins.map((el) => [resolve(el[0]), el[1]]) : void 0,
128
- devTarget: (_options == null ? void 0 : _options.devTarget) ?? "es2020",
129
- parserConfig: _options == null ? void 0 : _options.parserConfig,
130
- reactRefreshHost: _options == null ? void 0 : _options.reactRefreshHost,
131
- useAtYourOwnRisk_mutateSwcOptions: _options == null ? void 0 : _options.useAtYourOwnRisk_mutateSwcOptions,
132
- disableOxcRecommendation: _options == null ? void 0 : _options.disableOxcRecommendation
133
- };
134
- return [
135
- {
136
- name: "vite:react-swc:resolve-runtime",
137
- apply: "serve",
138
- enforce: "pre",
139
- // Run before Vite default resolve to avoid syscalls
140
- resolveId: {
141
- filter: { id: exactRegex(runtimePublicPath) },
142
- handler: (id) => id === runtimePublicPath ? id : void 0
143
- },
144
- load: {
145
- filter: { id: exactRegex(runtimePublicPath) },
146
- handler: (id) => id === runtimePublicPath ? readFileSync(
147
- join(_dirname, "refresh-runtime.js"),
148
- "utf-8"
149
- ).replace(
150
- /__README_URL__/g,
151
- "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc"
152
- ) : void 0
153
- }
154
- },
155
- {
156
- name: "vite:react-swc",
157
- apply: "serve",
158
- config: () => ({
159
- esbuild: false,
160
- // NOTE: oxc option only exists in rolldown-vite
161
- oxc: false,
162
- optimizeDeps: {
163
- include: [`${options.jsxImportSource}/jsx-dev-runtime`],
164
- ..."rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
165
- }
166
- }),
167
- configResolved(config) {
168
- if (config.server.hmr === false) hmrDisabled = true;
169
- const mdxIndex = config.plugins.findIndex(
170
- (p) => p.name === "@mdx-js/rollup"
171
- );
172
- if (mdxIndex !== -1 && mdxIndex > config.plugins.findIndex((p) => p.name === "vite:react-swc")) {
173
- throw new Error(
174
- "[vite:react-swc] The MDX plugin should be placed before this plugin"
175
- );
176
- }
177
- if ("rolldownVersion" in vite && !options.plugins && !options.useAtYourOwnRisk_mutateSwcOptions && !options.disableOxcRecommendation) {
178
- config.logger.warn(
179
- "[vite:react-swc] We recommend switching to `@vitejs/plugin-react-oxc` for improved performance as no swc plugins are used. More information at https://vite.dev/rolldown"
180
- );
181
- }
182
- },
183
- transformIndexHtml: (_, config) => {
184
- if (!hmrDisabled) {
185
- return [
186
- {
187
- tag: "script",
188
- attrs: { type: "module" },
189
- children: getPreambleCode(config.server.config.base)
190
- }
191
- ];
192
- }
193
- },
194
- async transform(code, _id, transformOptions) {
195
- const id = _id.split("?")[0];
196
- const refresh = !(transformOptions == null ? void 0 : transformOptions.ssr) && !hmrDisabled;
197
- const result = await transformWithOptions(
198
- id,
199
- code,
200
- options.devTarget,
201
- options,
202
- {
203
- refresh,
204
- development: true,
205
- runtime: "automatic",
206
- importSource: options.jsxImportSource
207
- }
208
- );
209
- if (!result) return;
210
- if (!refresh) return result;
211
- return addRefreshWrapper(
212
- result.code,
213
- result.map,
214
- "@vitejs/plugin-react-swc",
215
- id,
216
- options.reactRefreshHost
217
- );
218
- }
219
- },
220
- options.plugins ? {
221
- name: "vite:react-swc",
222
- apply: "build",
223
- enforce: "pre",
224
- // Run before esbuild
225
- config: (userConfig) => ({
226
- build: silenceUseClientWarning(userConfig)
227
- }),
228
- transform: (code, _id) => transformWithOptions(_id.split("?")[0], code, "esnext", options, {
229
- runtime: "automatic",
230
- importSource: options.jsxImportSource
231
- })
232
- } : {
233
- name: "vite:react-swc",
234
- apply: "build",
235
- config: (userConfig) => ({
236
- build: silenceUseClientWarning(userConfig),
237
- esbuild: {
238
- jsx: "automatic",
239
- jsxImportSource: options.jsxImportSource,
240
- tsconfigRaw: {
241
- compilerOptions: { useDefineForClassFields: true }
242
- }
243
- }
244
- })
245
- }
246
- ];
247
- };
248
- var transformWithOptions = async (id, code, target, options, reactConfig) => {
249
- const decorators = (options == null ? void 0 : options.tsDecorators) ?? false;
250
- const parser = options.parserConfig ? options.parserConfig(id) : id.endsWith(".tsx") ? { syntax: "typescript", tsx: true, decorators } : id.endsWith(".ts") || id.endsWith(".mts") ? { syntax: "typescript", tsx: false, decorators } : id.endsWith(".jsx") ? { syntax: "ecmascript", jsx: true } : id.endsWith(".mdx") ? (
251
- // JSX is required to trigger fast refresh transformations, even if MDX already transforms it
252
- { syntax: "ecmascript", jsx: true }
253
- ) : void 0;
254
- if (!parser) return;
255
- let result;
256
- try {
257
- const swcOptions = {
258
- filename: id,
259
- swcrc: false,
260
- configFile: false,
261
- sourceMaps: true,
262
- jsc: {
263
- target,
264
- parser,
265
- experimental: { plugins: options.plugins },
266
- transform: {
267
- useDefineForClassFields: true,
268
- react: reactConfig
269
- }
270
- }
271
- };
272
- if (options.useAtYourOwnRisk_mutateSwcOptions) {
273
- options.useAtYourOwnRisk_mutateSwcOptions(swcOptions);
274
- }
275
- result = await transform(code, swcOptions);
276
- } catch (e) {
277
- const message = e.message;
278
- const fileStartIndex = message.indexOf("\u256D\u2500[");
279
- if (fileStartIndex !== -1) {
280
- const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)\]/);
281
- if (match) {
282
- e.line = match[1];
283
- e.column = match[2];
284
- }
285
- }
286
- throw e;
287
- }
288
- return result;
289
- };
290
- var index_default = react;
291
- export {
292
- index_default as default
293
- };