@vitejs/plugin-react-swc 3.10.2 → 4.0.0-beta.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.d.ts CHANGED
@@ -1,54 +1,58 @@
1
- import { type JscTarget, type ParserConfig, type Options as SWCOptions } from '@swc/core';
2
- import type { PluginOption } from 'vite';
3
- type Options = {
4
- /**
5
- * Control where the JSX factory is imported from.
6
- * @default "react"
7
- */
8
- jsxImportSource?: string;
9
- /**
10
- * Enable TypeScript decorators. Requires experimentalDecorators in tsconfig.
11
- * @default false
12
- */
13
- tsDecorators?: boolean;
14
- /**
15
- * Use SWC plugins. Enable SWC at build time.
16
- * @default undefined
17
- */
18
- plugins?: [string, Record<string, any>][];
19
- /**
20
- * Set the target for SWC in dev. This can avoid to down-transpile private class method for example.
21
- * For production target, see https://vite.dev/config/build-options.html#build-target
22
- * @default "es2020"
23
- */
24
- devTarget?: JscTarget;
25
- /**
26
- * Override the default include list (.ts, .tsx, .mts, .jsx, .mdx).
27
- * This requires to redefine the config for any file you want to be included.
28
- * If you want to trigger fast refresh on compiled JS, use `jsx: true`.
29
- * Exclusion of node_modules should be handled by the function if needed.
30
- */
31
- parserConfig?: (id: string) => ParserConfig | undefined;
32
- /**
33
- * React Fast Refresh runtime URL prefix.
34
- * Useful in a module federation context to enable HMR by specifying
35
- * the host application URL in a Vite config of a remote application.
36
- * @example
37
- * reactRefreshHost: 'http://localhost:3000'
38
- */
39
- reactRefreshHost?: string;
40
- /**
41
- * The future of Vite is with OXC, and from the beginning this was a design choice
42
- * to not exposed too many specialties from SWC so that Vite React users can move to
43
- * another transformer later.
44
- * Also debugging why some specific version of decorators with some other unstable/legacy
45
- * feature doesn't work is not fun, so we won't provide support for it, hence the name `useAtYourOwnRisk`
46
- */
47
- useAtYourOwnRisk_mutateSwcOptions?: (options: SWCOptions) => void;
48
- /**
49
- * If set, disables the recommendation to use `@vitejs/plugin-react-oxc`
50
- */
51
- disableOxcRecommendation?: boolean;
1
+ import { JscTarget, Options, ParserConfig } from "@swc/core";
2
+ import { Plugin } from "vite";
3
+
4
+ //#region src/index.d.ts
5
+ type Options$1 = {
6
+ /**
7
+ * Control where the JSX factory is imported from.
8
+ * @default "react"
9
+ */
10
+ jsxImportSource?: string;
11
+ /**
12
+ * Enable TypeScript decorators. Requires experimentalDecorators in tsconfig.
13
+ * @default false
14
+ */
15
+ tsDecorators?: boolean;
16
+ /**
17
+ * Use SWC plugins. Enable SWC at build time.
18
+ * @default undefined
19
+ */
20
+ plugins?: [string, Record<string, any>][];
21
+ /**
22
+ * Set the target for SWC in dev. This can avoid to down-transpile private class method for example.
23
+ * For production target, see https://vite.dev/config/build-options.html#build-target
24
+ * @default "es2020"
25
+ */
26
+ devTarget?: JscTarget;
27
+ /**
28
+ * Override the default include list (.ts, .tsx, .mts, .jsx, .mdx).
29
+ * This requires to redefine the config for any file you want to be included.
30
+ * If you want to trigger fast refresh on compiled JS, use `jsx: true`.
31
+ * Exclusion of node_modules should be handled by the function if needed.
32
+ */
33
+ parserConfig?: (id: string) => ParserConfig | undefined;
34
+ /**
35
+ * React Fast Refresh runtime URL prefix.
36
+ * Useful in a module federation context to enable HMR by specifying
37
+ * the host application URL in a Vite config of a remote application.
38
+ * @example
39
+ * reactRefreshHost: 'http://localhost:3000'
40
+ */
41
+ reactRefreshHost?: string;
42
+ /**
43
+ * The future of Vite is with OXC, and from the beginning this was a design choice
44
+ * to not exposed too many specialties from SWC so that Vite React users can move to
45
+ * another transformer later.
46
+ * Also debugging why some specific version of decorators with some other unstable/legacy
47
+ * feature doesn't work is not fun, so we won't provide support for it, hence the name `useAtYourOwnRisk`
48
+ */
49
+ useAtYourOwnRisk_mutateSwcOptions?: (options: Options) => void;
50
+ /**
51
+ * If set, disables the recommendation to use `@vitejs/plugin-react`
52
+ */
53
+ disableOxcRecommendation?: boolean;
52
54
  };
53
- declare const react: (_options?: Options) => PluginOption[];
54
- export default react;
55
+ declare const react: (_options?: Options$1) => Plugin[];
56
+ declare function pluginForCjs(this: unknown, options: Options$1): Plugin[];
57
+ //#endregion
58
+ export { react as default, pluginForCjs as "module.exports" };
package/index.js ADDED
@@ -0,0 +1,242 @@
1
+ import { createRequire } from "node:module";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { transform } from "@swc/core";
6
+ import * as vite from "vite";
7
+ import { exactRegex } from "@rolldown/pluginutils";
8
+
9
+ //#region ../common/refresh-utils.ts
10
+ const runtimePublicPath = "/@react-refresh";
11
+ const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
12
+ const refreshContentRE = /\$RefreshReg\$\(/;
13
+ const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
14
+ injectIntoGlobalHook(window);
15
+ window.$RefreshReg$ = () => {};
16
+ window.$RefreshSig$ = () => (type) => type;`;
17
+ const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
18
+ const avoidSourceMapOption = Symbol();
19
+ function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
20
+ const hasRefresh = refreshContentRE.test(code);
21
+ const onlyReactComp = !hasRefresh && reactCompRE.test(code);
22
+ const normalizedMap = map === avoidSourceMapOption ? null : map;
23
+ if (!hasRefresh && !onlyReactComp) return {
24
+ code,
25
+ map: normalizedMap
26
+ };
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(`let prevRefreshReg;
32
+ let prevRefreshSig;
33
+
34
+ if (import.meta.hot && !inWebWorker) {
35
+ if (!window.$RefreshReg$) {
36
+ throw new Error(
37
+ "${pluginName} can't detect preamble. Something is wrong."
38
+ );
39
+ }
40
+
41
+ prevRefreshReg = window.$RefreshReg$;
42
+ prevRefreshSig = window.$RefreshSig$;
43
+ window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
44
+ window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
45
+ }
46
+
47
+ `, avoidSourceMap);
48
+ newCode = `${refreshHead}${newCode}
49
+
50
+ if (import.meta.hot && !inWebWorker) {
51
+ window.$RefreshReg$ = prevRefreshReg;
52
+ window.$RefreshSig$ = prevRefreshSig;
53
+ }
54
+ `;
55
+ if (newMap) newMap.mappings = ";".repeat(16) + newMap.mappings;
56
+ }
57
+ const sharedHead = removeLineBreaksIfNeeded(`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
58
+ const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
59
+
60
+ `, avoidSourceMap);
61
+ newCode = `${sharedHead}${newCode}
62
+
63
+ if (import.meta.hot && !inWebWorker) {
64
+ RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
65
+ RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(id)}, currentExports);
66
+ import.meta.hot.accept((nextExports) => {
67
+ if (!nextExports) return;
68
+ const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(id)}, currentExports, nextExports);
69
+ if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
70
+ });
71
+ });
72
+ }
73
+ `;
74
+ if (newMap) newMap.mappings = ";;;" + newMap.mappings;
75
+ return {
76
+ code: newCode,
77
+ map: newMap
78
+ };
79
+ }
80
+ function removeLineBreaksIfNeeded(code, enabled) {
81
+ return enabled ? code.replace(/\n/g, "") : code;
82
+ }
83
+
84
+ //#endregion
85
+ //#region ../common/warning.ts
86
+ const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
87
+ if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
88
+ if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
89
+ if (userConfig.build?.rollupOptions?.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
90
+ else defaultHandler(warning);
91
+ } } });
92
+
93
+ //#endregion
94
+ //#region src/index.ts
95
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
96
+ const resolve = createRequire(typeof __filename !== "undefined" ? __filename : import.meta.url).resolve;
97
+ const react = (_options) => {
98
+ let hmrDisabled = false;
99
+ const options = {
100
+ jsxImportSource: _options?.jsxImportSource ?? "react",
101
+ tsDecorators: _options?.tsDecorators,
102
+ plugins: _options?.plugins ? _options?.plugins.map((el) => [resolve(el[0]), el[1]]) : void 0,
103
+ devTarget: _options?.devTarget ?? "es2020",
104
+ parserConfig: _options?.parserConfig,
105
+ reactRefreshHost: _options?.reactRefreshHost,
106
+ useAtYourOwnRisk_mutateSwcOptions: _options?.useAtYourOwnRisk_mutateSwcOptions,
107
+ disableOxcRecommendation: _options?.disableOxcRecommendation
108
+ };
109
+ return [
110
+ {
111
+ name: "vite:react-swc:resolve-runtime",
112
+ apply: "serve",
113
+ enforce: "pre",
114
+ resolveId: {
115
+ filter: { id: exactRegex(runtimePublicPath) },
116
+ handler: (id) => id === runtimePublicPath ? id : void 0
117
+ },
118
+ load: {
119
+ filter: { id: exactRegex(runtimePublicPath) },
120
+ handler: (id) => id === runtimePublicPath ? readFileSync(join(_dirname, "refresh-runtime.js"), "utf-8").replace(/__README_URL__/g, "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc") : void 0
121
+ }
122
+ },
123
+ {
124
+ name: "vite:react-swc",
125
+ apply: "serve",
126
+ config: () => ({
127
+ esbuild: false,
128
+ oxc: false,
129
+ optimizeDeps: {
130
+ include: [`${options.jsxImportSource}/jsx-dev-runtime`],
131
+ ..."rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
132
+ }
133
+ }),
134
+ configResolved(config) {
135
+ if (config.server.hmr === false) hmrDisabled = true;
136
+ const mdxIndex = config.plugins.findIndex((p) => p.name === "@mdx-js/rollup");
137
+ if (mdxIndex !== -1 && mdxIndex > config.plugins.findIndex((p) => p.name === "vite:react-swc")) throw new Error("[vite:react-swc] The MDX plugin should be placed before this plugin");
138
+ if ("rolldownVersion" in vite && !options.plugins && !options.useAtYourOwnRisk_mutateSwcOptions && !options.disableOxcRecommendation) config.logger.warn("[vite:react-swc] We recommend switching to `@vitejs/plugin-react` for improved performance as no swc plugins are used. More information at https://vite.dev/rolldown");
139
+ },
140
+ transformIndexHtml: (_, config) => {
141
+ if (!hmrDisabled) return [{
142
+ tag: "script",
143
+ attrs: { type: "module" },
144
+ children: getPreambleCode(config.server.config.base)
145
+ }];
146
+ },
147
+ async transform(code, _id, transformOptions) {
148
+ const id = _id.split("?")[0];
149
+ const refresh = !transformOptions?.ssr && !hmrDisabled;
150
+ const result = await transformWithOptions(id, code, options.devTarget, options, {
151
+ refresh,
152
+ development: true,
153
+ runtime: "automatic",
154
+ importSource: options.jsxImportSource
155
+ });
156
+ if (!result) return;
157
+ if (!refresh) return result;
158
+ return addRefreshWrapper(result.code, result.map, "@vitejs/plugin-react-swc", id, options.reactRefreshHost);
159
+ }
160
+ },
161
+ options.plugins ? {
162
+ name: "vite:react-swc",
163
+ apply: "build",
164
+ enforce: "pre",
165
+ config: (userConfig) => ({ build: silenceUseClientWarning(userConfig) }),
166
+ transform: (code, _id) => transformWithOptions(_id.split("?")[0], code, "esnext", options, {
167
+ runtime: "automatic",
168
+ importSource: options.jsxImportSource
169
+ })
170
+ } : {
171
+ name: "vite:react-swc",
172
+ apply: "build",
173
+ config: (userConfig) => ({
174
+ build: silenceUseClientWarning(userConfig),
175
+ esbuild: {
176
+ jsx: "automatic",
177
+ jsxImportSource: options.jsxImportSource,
178
+ tsconfigRaw: { compilerOptions: { useDefineForClassFields: true } }
179
+ }
180
+ })
181
+ }
182
+ ];
183
+ };
184
+ const transformWithOptions = async (id, code, target, options, reactConfig) => {
185
+ const decorators = options?.tsDecorators ?? false;
186
+ const parser = options.parserConfig ? options.parserConfig(id) : id.endsWith(".tsx") ? {
187
+ syntax: "typescript",
188
+ tsx: true,
189
+ decorators
190
+ } : id.endsWith(".ts") || id.endsWith(".mts") ? {
191
+ syntax: "typescript",
192
+ tsx: false,
193
+ decorators
194
+ } : id.endsWith(".jsx") ? {
195
+ syntax: "ecmascript",
196
+ jsx: true
197
+ } : id.endsWith(".mdx") ? {
198
+ syntax: "ecmascript",
199
+ jsx: true
200
+ } : void 0;
201
+ if (!parser) return;
202
+ let result;
203
+ try {
204
+ const swcOptions = {
205
+ filename: id,
206
+ swcrc: false,
207
+ configFile: false,
208
+ sourceMaps: true,
209
+ jsc: {
210
+ target,
211
+ parser,
212
+ experimental: { plugins: options.plugins },
213
+ transform: {
214
+ useDefineForClassFields: true,
215
+ react: reactConfig
216
+ }
217
+ }
218
+ };
219
+ if (options.useAtYourOwnRisk_mutateSwcOptions) options.useAtYourOwnRisk_mutateSwcOptions(swcOptions);
220
+ result = await transform(code, swcOptions);
221
+ } catch (e) {
222
+ const message = e.message;
223
+ const fileStartIndex = message.indexOf("╭─[");
224
+ if (fileStartIndex !== -1) {
225
+ const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)\]/);
226
+ if (match) {
227
+ e.line = match[1];
228
+ e.column = match[2];
229
+ }
230
+ }
231
+ throw e;
232
+ }
233
+ return result;
234
+ };
235
+ var src_default = react;
236
+ function pluginForCjs(options) {
237
+ return react.call(this, options);
238
+ }
239
+ Object.assign(pluginForCjs, { default: pluginForCjs });
240
+
241
+ //#endregion
242
+ export { src_default as default, pluginForCjs as "module.exports" };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-react-swc",
3
- "version": "3.10.2",
3
+ "version": "4.0.0-beta.0",
4
4
  "license": "MIT",
5
5
  "author": "Arnaud Barré (https://github.com/ArnaudBarre)",
6
6
  "description": "Speed up your Vite dev server with SWC",
@@ -13,6 +13,9 @@
13
13
  "fast refresh"
14
14
  ],
15
15
  "type": "module",
16
+ "engines": {
17
+ "node": "^20.19.0 || >=22.12.0"
18
+ },
16
19
  "repository": {
17
20
  "type": "git",
18
21
  "url": "git+https://github.com/vitejs/vite-plugin-react.git",
@@ -23,20 +26,11 @@
23
26
  },
24
27
  "homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc#readme",
25
28
  "dependencies": {
26
- "@rolldown/pluginutils": "1.0.0-beta.11",
27
- "@swc/core": "^1.11.31"
29
+ "@rolldown/pluginutils": "1.0.0-beta.29",
30
+ "@swc/core": "^1.13.2"
28
31
  },
29
32
  "peerDependencies": {
30
- "vite": "^4 || ^5 || ^6 || ^7.0.0-beta.0"
33
+ "vite": "^4 || ^5 || ^6 || ^7"
31
34
  },
32
- "main": "index.cjs",
33
- "types": "index.d.ts",
34
- "module": "index.mjs",
35
- "exports": {
36
- ".": {
37
- "types": "./index.d.ts",
38
- "require": "./index.cjs",
39
- "import": "./index.mjs"
40
- }
41
- }
35
+ "exports": "./index.js"
42
36
  }