@vitejs/plugin-react-swc 3.11.0 → 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
@@ -48,10 +48,11 @@ type Options$1 = {
48
48
  */
49
49
  useAtYourOwnRisk_mutateSwcOptions?: (options: Options) => void;
50
50
  /**
51
- * If set, disables the recommendation to use `@vitejs/plugin-react-oxc`
51
+ * If set, disables the recommendation to use `@vitejs/plugin-react`
52
52
  */
53
53
  disableOxcRecommendation?: boolean;
54
54
  };
55
55
  declare const react: (_options?: Options$1) => Plugin[];
56
+ declare function pluginForCjs(this: unknown, options: Options$1): Plugin[];
56
57
  //#endregion
57
- export { react as default };
58
+ export { react as default, pluginForCjs as "module.exports" };
package/index.js CHANGED
@@ -135,7 +135,7 @@ const react = (_options) => {
135
135
  if (config.server.hmr === false) hmrDisabled = true;
136
136
  const mdxIndex = config.plugins.findIndex((p) => p.name === "@mdx-js/rollup");
137
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-oxc` for improved performance as no swc plugins are used. More information at https://vite.dev/rolldown");
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
139
  },
140
140
  transformIndexHtml: (_, config) => {
141
141
  if (!hmrDisabled) return [{
@@ -233,6 +233,10 @@ const transformWithOptions = async (id, code, target, options, reactConfig) => {
233
233
  return result;
234
234
  };
235
235
  var src_default = react;
236
+ function pluginForCjs(options) {
237
+ return react.call(this, options);
238
+ }
239
+ Object.assign(pluginForCjs, { default: pluginForCjs });
236
240
 
237
241
  //#endregion
238
- export { src_default as default };
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.11.0",
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,19 +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.27",
27
- "@swc/core": "^1.12.11"
29
+ "@rolldown/pluginutils": "1.0.0-beta.29",
30
+ "@swc/core": "^1.13.2"
28
31
  },
29
32
  "peerDependencies": {
30
33
  "vite": "^4 || ^5 || ^6 || ^7"
31
34
  },
32
- "main": "index.cjs",
33
- "types": "index.d.ts",
34
- "module": "index.js",
35
- "exports": {
36
- ".": {
37
- "require": "./index.cjs",
38
- "import": "./index.js"
39
- }
40
- }
35
+ "exports": "./index.js"
41
36
  }
package/index.cjs DELETED
@@ -1,262 +0,0 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
- key = keys[i];
11
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
- get: ((k) => from[k]).bind(null, key),
13
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
- });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
- value: mod,
20
- enumerable: true
21
- }) : target, mod));
22
-
23
- //#endregion
24
- const node_fs = __toESM(require("node:fs"));
25
- const node_path = __toESM(require("node:path"));
26
- const node_url = __toESM(require("node:url"));
27
- const node_module = __toESM(require("node:module"));
28
- const __swc_core = __toESM(require("@swc/core"));
29
- const vite = __toESM(require("vite"));
30
- const __rolldown_pluginutils = __toESM(require("@rolldown/pluginutils"));
31
-
32
- //#region ../common/refresh-utils.ts
33
- const runtimePublicPath = "/@react-refresh";
34
- const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
35
- const refreshContentRE = /\$RefreshReg\$\(/;
36
- const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
37
- injectIntoGlobalHook(window);
38
- window.$RefreshReg$ = () => {};
39
- window.$RefreshSig$ = () => (type) => type;`;
40
- const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
41
- const avoidSourceMapOption = Symbol();
42
- function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
43
- const hasRefresh = refreshContentRE.test(code);
44
- const onlyReactComp = !hasRefresh && reactCompRE.test(code);
45
- const normalizedMap = map === avoidSourceMapOption ? null : map;
46
- if (!hasRefresh && !onlyReactComp) return {
47
- code,
48
- map: normalizedMap
49
- };
50
- const avoidSourceMap = map === avoidSourceMapOption;
51
- const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
52
- let newCode = code;
53
- if (hasRefresh) {
54
- const refreshHead = removeLineBreaksIfNeeded(`let prevRefreshReg;
55
- let prevRefreshSig;
56
-
57
- if (import.meta.hot && !inWebWorker) {
58
- if (!window.$RefreshReg$) {
59
- throw new Error(
60
- "${pluginName} can't detect preamble. Something is wrong."
61
- );
62
- }
63
-
64
- prevRefreshReg = window.$RefreshReg$;
65
- prevRefreshSig = window.$RefreshSig$;
66
- window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
67
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
68
- }
69
-
70
- `, avoidSourceMap);
71
- newCode = `${refreshHead}${newCode}
72
-
73
- if (import.meta.hot && !inWebWorker) {
74
- window.$RefreshReg$ = prevRefreshReg;
75
- window.$RefreshSig$ = prevRefreshSig;
76
- }
77
- `;
78
- if (newMap) newMap.mappings = ";".repeat(16) + newMap.mappings;
79
- }
80
- const sharedHead = removeLineBreaksIfNeeded(`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
81
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
82
-
83
- `, avoidSourceMap);
84
- newCode = `${sharedHead}${newCode}
85
-
86
- if (import.meta.hot && !inWebWorker) {
87
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
88
- RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(id)}, currentExports);
89
- import.meta.hot.accept((nextExports) => {
90
- if (!nextExports) return;
91
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(id)}, currentExports, nextExports);
92
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
93
- });
94
- });
95
- }
96
- `;
97
- if (newMap) newMap.mappings = ";;;" + newMap.mappings;
98
- return {
99
- code: newCode,
100
- map: newMap
101
- };
102
- }
103
- function removeLineBreaksIfNeeded(code, enabled) {
104
- return enabled ? code.replace(/\n/g, "") : code;
105
- }
106
-
107
- //#endregion
108
- //#region ../common/warning.ts
109
- const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
110
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
111
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
112
- if (userConfig.build?.rollupOptions?.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
113
- else defaultHandler(warning);
114
- } } });
115
-
116
- //#endregion
117
- //#region src/index.ts
118
- const _dirname = typeof __dirname !== "undefined" ? __dirname : (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
119
- const resolve = (0, node_module.createRequire)(typeof __filename !== "undefined" ? __filename : require("url").pathToFileURL(__filename).href).resolve;
120
- const react = (_options) => {
121
- let hmrDisabled = false;
122
- const options = {
123
- jsxImportSource: _options?.jsxImportSource ?? "react",
124
- tsDecorators: _options?.tsDecorators,
125
- plugins: _options?.plugins ? _options?.plugins.map((el) => [resolve(el[0]), el[1]]) : void 0,
126
- devTarget: _options?.devTarget ?? "es2020",
127
- parserConfig: _options?.parserConfig,
128
- reactRefreshHost: _options?.reactRefreshHost,
129
- useAtYourOwnRisk_mutateSwcOptions: _options?.useAtYourOwnRisk_mutateSwcOptions,
130
- disableOxcRecommendation: _options?.disableOxcRecommendation
131
- };
132
- return [
133
- {
134
- name: "vite:react-swc:resolve-runtime",
135
- apply: "serve",
136
- enforce: "pre",
137
- resolveId: {
138
- filter: { id: (0, __rolldown_pluginutils.exactRegex)(runtimePublicPath) },
139
- handler: (id) => id === runtimePublicPath ? id : void 0
140
- },
141
- load: {
142
- filter: { id: (0, __rolldown_pluginutils.exactRegex)(runtimePublicPath) },
143
- handler: (id) => id === runtimePublicPath ? (0, node_fs.readFileSync)((0, node_path.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
144
- }
145
- },
146
- {
147
- name: "vite:react-swc",
148
- apply: "serve",
149
- config: () => ({
150
- esbuild: false,
151
- oxc: false,
152
- optimizeDeps: {
153
- include: [`${options.jsxImportSource}/jsx-dev-runtime`],
154
- ..."rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
155
- }
156
- }),
157
- configResolved(config) {
158
- if (config.server.hmr === false) hmrDisabled = true;
159
- const mdxIndex = config.plugins.findIndex((p) => p.name === "@mdx-js/rollup");
160
- 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");
161
- if ("rolldownVersion" in vite && !options.plugins && !options.useAtYourOwnRisk_mutateSwcOptions && !options.disableOxcRecommendation) config.logger.warn("[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");
162
- },
163
- transformIndexHtml: (_, config) => {
164
- if (!hmrDisabled) return [{
165
- tag: "script",
166
- attrs: { type: "module" },
167
- children: getPreambleCode(config.server.config.base)
168
- }];
169
- },
170
- async transform(code, _id, transformOptions) {
171
- const id = _id.split("?")[0];
172
- const refresh = !transformOptions?.ssr && !hmrDisabled;
173
- const result = await transformWithOptions(id, code, options.devTarget, options, {
174
- refresh,
175
- development: true,
176
- runtime: "automatic",
177
- importSource: options.jsxImportSource
178
- });
179
- if (!result) return;
180
- if (!refresh) return result;
181
- return addRefreshWrapper(result.code, result.map, "@vitejs/plugin-react-swc", id, options.reactRefreshHost);
182
- }
183
- },
184
- options.plugins ? {
185
- name: "vite:react-swc",
186
- apply: "build",
187
- enforce: "pre",
188
- config: (userConfig) => ({ build: silenceUseClientWarning(userConfig) }),
189
- transform: (code, _id) => transformWithOptions(_id.split("?")[0], code, "esnext", options, {
190
- runtime: "automatic",
191
- importSource: options.jsxImportSource
192
- })
193
- } : {
194
- name: "vite:react-swc",
195
- apply: "build",
196
- config: (userConfig) => ({
197
- build: silenceUseClientWarning(userConfig),
198
- esbuild: {
199
- jsx: "automatic",
200
- jsxImportSource: options.jsxImportSource,
201
- tsconfigRaw: { compilerOptions: { useDefineForClassFields: true } }
202
- }
203
- })
204
- }
205
- ];
206
- };
207
- const transformWithOptions = async (id, code, target, options, reactConfig) => {
208
- const decorators = options?.tsDecorators ?? false;
209
- const parser = options.parserConfig ? options.parserConfig(id) : id.endsWith(".tsx") ? {
210
- syntax: "typescript",
211
- tsx: true,
212
- decorators
213
- } : id.endsWith(".ts") || id.endsWith(".mts") ? {
214
- syntax: "typescript",
215
- tsx: false,
216
- decorators
217
- } : id.endsWith(".jsx") ? {
218
- syntax: "ecmascript",
219
- jsx: true
220
- } : id.endsWith(".mdx") ? {
221
- syntax: "ecmascript",
222
- jsx: true
223
- } : void 0;
224
- if (!parser) return;
225
- let result;
226
- try {
227
- const swcOptions = {
228
- filename: id,
229
- swcrc: false,
230
- configFile: false,
231
- sourceMaps: true,
232
- jsc: {
233
- target,
234
- parser,
235
- experimental: { plugins: options.plugins },
236
- transform: {
237
- useDefineForClassFields: true,
238
- react: reactConfig
239
- }
240
- }
241
- };
242
- if (options.useAtYourOwnRisk_mutateSwcOptions) options.useAtYourOwnRisk_mutateSwcOptions(swcOptions);
243
- result = await (0, __swc_core.transform)(code, swcOptions);
244
- } catch (e) {
245
- const message = e.message;
246
- const fileStartIndex = message.indexOf("╭─[");
247
- if (fileStartIndex !== -1) {
248
- const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)\]/);
249
- if (match) {
250
- e.line = match[1];
251
- e.column = match[2];
252
- }
253
- }
254
- throw e;
255
- }
256
- return result;
257
- };
258
- var src_default = react;
259
-
260
- //#endregion
261
- module.exports = src_default;
262
- module.exports.default = module.exports
package/index.d.cts DELETED
@@ -1,57 +0,0 @@
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-oxc`
52
- */
53
- disableOxcRecommendation?: boolean;
54
- };
55
- declare const react: (_options?: Options$1) => Plugin[];
56
- //#endregion
57
- export { react as default };