@vitejs/plugin-react-swc 3.10.1 → 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,286 +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 { exactRegex } from "@rolldown/pluginutils";
117
- var _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
118
- var resolve = createRequire(
119
- typeof __filename !== "undefined" ? __filename : import.meta.url
120
- ).resolve;
121
- var react = (_options) => {
122
- let hmrDisabled = false;
123
- const options = {
124
- jsxImportSource: (_options == null ? void 0 : _options.jsxImportSource) ?? "react",
125
- tsDecorators: _options == null ? void 0 : _options.tsDecorators,
126
- plugins: (_options == null ? void 0 : _options.plugins) ? _options == null ? void 0 : _options.plugins.map((el) => [resolve(el[0]), el[1]]) : void 0,
127
- devTarget: (_options == null ? void 0 : _options.devTarget) ?? "es2020",
128
- parserConfig: _options == null ? void 0 : _options.parserConfig,
129
- reactRefreshHost: _options == null ? void 0 : _options.reactRefreshHost,
130
- useAtYourOwnRisk_mutateSwcOptions: _options == null ? void 0 : _options.useAtYourOwnRisk_mutateSwcOptions
131
- };
132
- return [
133
- {
134
- name: "vite:react-swc:resolve-runtime",
135
- apply: "serve",
136
- enforce: "pre",
137
- // Run before Vite default resolve to avoid syscalls
138
- resolveId: {
139
- filter: { id: exactRegex(runtimePublicPath) },
140
- handler: (id) => id === runtimePublicPath ? id : void 0
141
- },
142
- load: {
143
- filter: { id: exactRegex(runtimePublicPath) },
144
- handler: (id) => id === runtimePublicPath ? readFileSync(
145
- join(_dirname, "refresh-runtime.js"),
146
- "utf-8"
147
- ).replace(
148
- /__README_URL__/g,
149
- "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc"
150
- ) : void 0
151
- }
152
- },
153
- {
154
- name: "vite:react-swc",
155
- apply: "serve",
156
- config: () => ({
157
- esbuild: false,
158
- // NOTE: oxc option only exists in rolldown-vite
159
- oxc: false,
160
- optimizeDeps: {
161
- include: [`${options.jsxImportSource}/jsx-dev-runtime`],
162
- esbuildOptions: { jsx: "automatic" }
163
- }
164
- }),
165
- configResolved(config) {
166
- if (config.server.hmr === false) hmrDisabled = true;
167
- const mdxIndex = config.plugins.findIndex(
168
- (p) => p.name === "@mdx-js/rollup"
169
- );
170
- if (mdxIndex !== -1 && mdxIndex > config.plugins.findIndex((p) => p.name === "vite:react-swc")) {
171
- throw new Error(
172
- "[vite:react-swc] The MDX plugin should be placed before this plugin"
173
- );
174
- }
175
- },
176
- transformIndexHtml: (_, config) => {
177
- if (!hmrDisabled) {
178
- return [
179
- {
180
- tag: "script",
181
- attrs: { type: "module" },
182
- children: getPreambleCode(config.server.config.base)
183
- }
184
- ];
185
- }
186
- },
187
- async transform(code, _id, transformOptions) {
188
- const id = _id.split("?")[0];
189
- const refresh = !(transformOptions == null ? void 0 : transformOptions.ssr) && !hmrDisabled;
190
- const result = await transformWithOptions(
191
- id,
192
- code,
193
- options.devTarget,
194
- options,
195
- {
196
- refresh,
197
- development: true,
198
- runtime: "automatic",
199
- importSource: options.jsxImportSource
200
- }
201
- );
202
- if (!result) return;
203
- if (!refresh) return result;
204
- return addRefreshWrapper(
205
- result.code,
206
- result.map,
207
- "@vitejs/plugin-react-swc",
208
- id,
209
- options.reactRefreshHost
210
- );
211
- }
212
- },
213
- options.plugins ? {
214
- name: "vite:react-swc",
215
- apply: "build",
216
- enforce: "pre",
217
- // Run before esbuild
218
- config: (userConfig) => ({
219
- build: silenceUseClientWarning(userConfig)
220
- }),
221
- transform: (code, _id) => transformWithOptions(_id.split("?")[0], code, "esnext", options, {
222
- runtime: "automatic",
223
- importSource: options.jsxImportSource
224
- })
225
- } : {
226
- name: "vite:react-swc",
227
- apply: "build",
228
- config: (userConfig) => ({
229
- build: silenceUseClientWarning(userConfig),
230
- esbuild: {
231
- jsx: "automatic",
232
- jsxImportSource: options.jsxImportSource,
233
- tsconfigRaw: {
234
- compilerOptions: { useDefineForClassFields: true }
235
- }
236
- }
237
- })
238
- }
239
- ];
240
- };
241
- var transformWithOptions = async (id, code, target, options, reactConfig) => {
242
- const decorators = (options == null ? void 0 : options.tsDecorators) ?? false;
243
- 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") ? (
244
- // JSX is required to trigger fast refresh transformations, even if MDX already transforms it
245
- { syntax: "ecmascript", jsx: true }
246
- ) : void 0;
247
- if (!parser) return;
248
- let result;
249
- try {
250
- const swcOptions = {
251
- filename: id,
252
- swcrc: false,
253
- configFile: false,
254
- sourceMaps: true,
255
- jsc: {
256
- target,
257
- parser,
258
- experimental: { plugins: options.plugins },
259
- transform: {
260
- useDefineForClassFields: true,
261
- react: reactConfig
262
- }
263
- }
264
- };
265
- if (options.useAtYourOwnRisk_mutateSwcOptions) {
266
- options.useAtYourOwnRisk_mutateSwcOptions(swcOptions);
267
- }
268
- result = await transform(code, swcOptions);
269
- } catch (e) {
270
- const message = e.message;
271
- const fileStartIndex = message.indexOf("\u256D\u2500[");
272
- if (fileStartIndex !== -1) {
273
- const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)\]/);
274
- if (match) {
275
- e.line = match[1];
276
- e.column = match[2];
277
- }
278
- }
279
- throw e;
280
- }
281
- return result;
282
- };
283
- var index_default = react;
284
- export {
285
- index_default as default
286
- };