@vitejs/plugin-react-swc 3.8.1 → 3.9.0-beta.3

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/README.md CHANGED
@@ -14,12 +14,12 @@ npm i -D @vitejs/plugin-react-swc
14
14
  ## Usage
15
15
 
16
16
  ```ts
17
- import { defineConfig } from "vite";
18
- import react from "@vitejs/plugin-react-swc";
17
+ import { defineConfig } from 'vite'
18
+ import react from '@vitejs/plugin-react-swc'
19
19
 
20
20
  export default defineConfig({
21
21
  plugins: [react()],
22
- });
22
+ })
23
23
  ```
24
24
 
25
25
  ## Caveats
@@ -29,7 +29,7 @@ This plugin has limited options to enable good performances and be transpiler ag
29
29
  - [useDefineForClassFields](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier) is always activated, as this matches the current ECMAScript spec
30
30
  - `jsx runtime` is always `automatic`
31
31
  - In development:
32
- - esbuild is disabled, so the [esbuild configuration](https://vitejs.dev/config/shared-options.html#esbuild) has no effect
32
+ - esbuild is disabled, so the [esbuild configuration](https://vite.dev/config/shared-options.html#esbuild) has no effect
33
33
  - `target` is ignored and defaults to `es2020` (see [`devTarget`](#devtarget))
34
34
  - JS files are not transformed
35
35
  - tsconfig is not resolved, so properties other than the ones listed above behaves like TS defaults
@@ -43,7 +43,7 @@ Control where the JSX factory is imported from.
43
43
  `@default` "react"
44
44
 
45
45
  ```ts
46
- react({ jsxImportSource: "@emotion/react" });
46
+ react({ jsxImportSource: '@emotion/react' })
47
47
  ```
48
48
 
49
49
  ### tsDecorators
@@ -53,7 +53,7 @@ Enable TypeScript decorators. Requires `experimentalDecorators` in tsconfig.
53
53
  `@default` false
54
54
 
55
55
  ```ts
56
- react({ tsDecorators: true });
56
+ react({ tsDecorators: true })
57
57
  ```
58
58
 
59
59
  ### plugins
@@ -61,19 +61,19 @@ react({ tsDecorators: true });
61
61
  Use SWC plugins. Enable SWC at build time.
62
62
 
63
63
  ```ts
64
- react({ plugins: [["@swc/plugin-styled-components", {}]] });
64
+ react({ plugins: [['@swc/plugin-styled-components', {}]] })
65
65
  ```
66
66
 
67
67
  ### devTarget
68
68
 
69
69
  Set the target for SWC in dev. This can avoid to down-transpile private class method for example.
70
70
 
71
- For production target, see https://vitejs.dev/config/build-options.html#build-target.
71
+ For production target, see https://vite.dev/config/build-options.html#build-target.
72
72
 
73
73
  `@default` "es2020"
74
74
 
75
75
  ```ts
76
- react({ devTarget: "es2022" });
76
+ react({ devTarget: 'es2022' })
77
77
  ```
78
78
 
79
79
  ### parserConfig
@@ -87,12 +87,22 @@ If you want to trigger fast refresh on compiled JS, use `jsx: true`. Exclusion o
87
87
  ```ts
88
88
  react({
89
89
  parserConfig(id) {
90
- if (id.endsWith(".res")) return { syntax: "ecmascript", jsx: true };
91
- if (id.endsWith(".ts")) return { syntax: "typescript", tsx: false };
90
+ if (id.endsWith('.res')) return { syntax: 'ecmascript', jsx: true }
91
+ if (id.endsWith('.ts')) return { syntax: 'typescript', tsx: false }
92
92
  },
93
- });
93
+ })
94
94
  ```
95
95
 
96
+ ### reactRefreshHost
97
+
98
+ The `reactRefreshHost` option is only necessary in a module federation context. It enables HMR to work between a remote & host application. In your remote Vite config, you would add your host origin:
99
+
100
+ ```js
101
+ react({ reactRefreshHost: 'http://localhost:3000' })
102
+ ```
103
+
104
+ Under the hood, this simply updates the React Fash Refresh runtime URL from `/@react-refresh` to `http://localhost:3000/@react-refresh` to ensure there is only one Refresh runtime across the whole application. Note that if you define `base` option in the host application, you need to include it in the option, like: `http://localhost:3000/{base}`.
105
+
96
106
  ### useAtYourOwnRisk_mutateSwcOptions
97
107
 
98
108
  The future of Vite is with OXC, and from the beginning this was a design choice to not exposed too many specialties from SWC so that Vite React users can move to another transformer later.
@@ -101,10 +111,10 @@ Also debugging why some specific version of decorators with some other unstable/
101
111
  ```ts
102
112
  react({
103
113
  useAtYourOwnRisk_mutateSwcOptions(options) {
104
- options.jsc.parser.decorators = true;
105
- options.jsc.transform.decoratorVersion = "2022-03";
114
+ options.jsc.parser.decorators = true
115
+ options.jsc.transform.decoratorVersion = '2022-03'
106
116
  },
107
- });
117
+ })
108
118
  ```
109
119
 
110
120
  ## Consistent components exports
package/index.cjs CHANGED
@@ -1,21 +1,121 @@
1
1
  // src/index.ts
2
- var import_fs = require("fs");
3
- var import_path = require("path");
4
- var import_url = require("url");
2
+ var import_node_fs = require("fs");
3
+ var import_node_path = require("path");
4
+ var import_node_url = require("url");
5
+ var import_node_module = require("module");
5
6
  var import_core = require("@swc/core");
6
- var import_module = require("module");
7
- var import_meta = {};
7
+
8
+ // ../common/refresh-utils.ts
8
9
  var runtimePublicPath = "/@react-refresh";
9
- var preambleCode = `import { injectIntoGlobalHook } from "__PATH__";
10
+ var reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
11
+ var refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
12
+ var preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
13
+ 1
14
+ )}"
10
15
  injectIntoGlobalHook(window);
11
16
  window.$RefreshReg$ = () => {};
12
17
  window.$RefreshSig$ = () => (type) => type;`;
13
- var _dirname = typeof __dirname !== "undefined" ? __dirname : (0, import_path.dirname)((0, import_url.fileURLToPath)(import_meta.url));
14
- var resolve = (0, import_module.createRequire)(
18
+ var getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
19
+ var avoidSourceMapOption = Symbol();
20
+ function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
21
+ const hasRefresh = refreshContentRE.test(code);
22
+ const onlyReactComp = !hasRefresh && reactCompRE.test(code);
23
+ const normalizedMap = map === avoidSourceMapOption ? null : map;
24
+ if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
25
+ const avoidSourceMap = map === avoidSourceMapOption;
26
+ const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
27
+ let newCode = code;
28
+ if (hasRefresh) {
29
+ const refreshHead = removeLineBreaksIfNeeded(
30
+ `let prevRefreshReg;
31
+ let prevRefreshSig;
32
+
33
+ if (import.meta.hot && !inWebWorker) {
34
+ if (!window.$RefreshReg$) {
35
+ throw new Error(
36
+ "${pluginName} can't detect preamble. Something is wrong."
37
+ );
38
+ }
39
+
40
+ prevRefreshReg = window.$RefreshReg$;
41
+ prevRefreshSig = window.$RefreshSig$;
42
+ window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
43
+ window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
44
+ }
45
+
46
+ `,
47
+ avoidSourceMap
48
+ );
49
+ newCode = `${refreshHead}${newCode}
50
+
51
+ if (import.meta.hot && !inWebWorker) {
52
+ window.$RefreshReg$ = prevRefreshReg;
53
+ window.$RefreshSig$ = prevRefreshSig;
54
+ }
55
+ `;
56
+ if (newMap) {
57
+ newMap.mappings = ";".repeat(16) + newMap.mappings;
58
+ }
59
+ }
60
+ const sharedHead = removeLineBreaksIfNeeded(
61
+ `import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
62
+ const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
63
+
64
+ `,
65
+ avoidSourceMap
66
+ );
67
+ newCode = `${sharedHead}${newCode}
68
+
69
+ if (import.meta.hot && !inWebWorker) {
70
+ RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
71
+ RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
72
+ id
73
+ )}, currentExports);
74
+ import.meta.hot.accept((nextExports) => {
75
+ if (!nextExports) return;
76
+ const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
77
+ id
78
+ )}, currentExports, nextExports);
79
+ if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
80
+ });
81
+ });
82
+ }
83
+ `;
84
+ if (newMap) {
85
+ newMap.mappings = ";;;" + newMap.mappings;
86
+ }
87
+ return { code: newCode, map: newMap };
88
+ }
89
+ function removeLineBreaksIfNeeded(code, enabled) {
90
+ return enabled ? code.replace(/\n/g, "") : code;
91
+ }
92
+
93
+ // ../common/warning.ts
94
+ var silenceUseClientWarning = (userConfig) => ({
95
+ rollupOptions: {
96
+ onwarn(warning, defaultHandler) {
97
+ var _a, _b;
98
+ if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
99
+ return;
100
+ }
101
+ if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
102
+ return;
103
+ }
104
+ if ((_b = (_a = userConfig.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.onwarn) {
105
+ userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
106
+ } else {
107
+ defaultHandler(warning);
108
+ }
109
+ }
110
+ }
111
+ });
112
+
113
+ // src/index.ts
114
+ var import_meta = {};
115
+ var _dirname = typeof __dirname !== "undefined" ? __dirname : (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
116
+ var resolve = (0, import_node_module.createRequire)(
15
117
  typeof __filename !== "undefined" ? __filename : import_meta.url
16
118
  ).resolve;
17
- var reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
18
- var refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
19
119
  var react = (_options) => {
20
120
  let hmrDisabled = false;
21
121
  const options = {
@@ -24,6 +124,7 @@ var react = (_options) => {
24
124
  plugins: (_options == null ? void 0 : _options.plugins) ? _options == null ? void 0 : _options.plugins.map((el) => [resolve(el[0]), el[1]]) : void 0,
25
125
  devTarget: (_options == null ? void 0 : _options.devTarget) ?? "es2020",
26
126
  parserConfig: _options == null ? void 0 : _options.parserConfig,
127
+ reactRefreshHost: _options == null ? void 0 : _options.reactRefreshHost,
27
128
  useAtYourOwnRisk_mutateSwcOptions: _options == null ? void 0 : _options.useAtYourOwnRisk_mutateSwcOptions
28
129
  };
29
130
  return [
@@ -33,7 +134,10 @@ var react = (_options) => {
33
134
  enforce: "pre",
34
135
  // Run before Vite default resolve to avoid syscalls
35
136
  resolveId: (id) => id === runtimePublicPath ? id : void 0,
36
- load: (id) => id === runtimePublicPath ? (0, import_fs.readFileSync)((0, import_path.join)(_dirname, "refresh-runtime.js"), "utf-8") : void 0
137
+ load: (id) => id === runtimePublicPath ? (0, import_node_fs.readFileSync)((0, import_node_path.join)(_dirname, "refresh-runtime.js"), "utf-8").replace(
138
+ /__README_URL__/g,
139
+ "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc"
140
+ ) : void 0
37
141
  },
38
142
  {
39
143
  name: "vite:react-swc",
@@ -60,10 +164,7 @@ var react = (_options) => {
60
164
  {
61
165
  tag: "script",
62
166
  attrs: { type: "module" },
63
- children: preambleCode.replace(
64
- "__PATH__",
65
- config.server.config.base + runtimePublicPath.slice(1)
66
- )
167
+ children: getPreambleCode(config.server.config.base)
67
168
  }
68
169
  ],
69
170
  async transform(code, _id, transformOptions) {
@@ -83,38 +184,13 @@ var react = (_options) => {
83
184
  );
84
185
  if (!result) return;
85
186
  if (!refresh) return result;
86
- const hasRefresh = refreshContentRE.test(result.code);
87
- if (!hasRefresh && !reactCompRE.test(result.code)) return result;
88
- const sourceMap = JSON.parse(result.map);
89
- sourceMap.mappings = ";;" + sourceMap.mappings;
90
- result.code = `import * as RefreshRuntime from "${runtimePublicPath}";
91
-
92
- ${result.code}`;
93
- if (hasRefresh) {
94
- sourceMap.mappings = ";;;;;;" + sourceMap.mappings;
95
- result.code = `if (!window.$RefreshReg$) throw new Error("React refresh preamble was not loaded. Something is wrong.");
96
- const prevRefreshReg = window.$RefreshReg$;
97
- const prevRefreshSig = window.$RefreshSig$;
98
- window.$RefreshReg$ = RefreshRuntime.getRefreshReg("${id}");
99
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
100
-
101
- ${result.code}
102
-
103
- window.$RefreshReg$ = prevRefreshReg;
104
- window.$RefreshSig$ = prevRefreshSig;
105
- `;
106
- }
107
- result.code += `
108
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
109
- RefreshRuntime.registerExportsForReactRefresh("${id}", currentExports);
110
- import.meta.hot.accept((nextExports) => {
111
- if (!nextExports) return;
112
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate("${id}", currentExports, nextExports);
113
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
114
- });
115
- });
116
- `;
117
- return { code: result.code, map: sourceMap };
187
+ return addRefreshWrapper(
188
+ result.code,
189
+ result.map,
190
+ "@vitejs/plugin-react-swc",
191
+ id,
192
+ options.reactRefreshHost
193
+ );
118
194
  }
119
195
  },
120
196
  options.plugins ? {
@@ -177,7 +253,7 @@ var transformWithOptions = async (id, code, target, options, reactConfig) => {
177
253
  const message = e.message;
178
254
  const fileStartIndex = message.indexOf("\u256D\u2500[");
179
255
  if (fileStartIndex !== -1) {
180
- const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)]/);
256
+ const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)\]/);
181
257
  if (match) {
182
258
  e.line = match[1];
183
259
  e.column = match[2];
@@ -187,24 +263,6 @@ var transformWithOptions = async (id, code, target, options, reactConfig) => {
187
263
  }
188
264
  return result;
189
265
  };
190
- var silenceUseClientWarning = (userConfig) => ({
191
- rollupOptions: {
192
- onwarn(warning, defaultHandler) {
193
- var _a, _b;
194
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
195
- return;
196
- }
197
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
198
- return;
199
- }
200
- if ((_b = (_a = userConfig.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.onwarn) {
201
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
202
- } else {
203
- defaultHandler(warning);
204
- }
205
- }
206
- }
207
- });
208
266
  var src_default = react;
209
267
 
210
268
  // <stdin>
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { type ParserConfig, type JscTarget, type Options as SWCOptions } from "@swc/core";
2
- import type { PluginOption } from "vite";
1
+ import { type JscTarget, type ParserConfig, type Options as SWCOptions } from '@swc/core';
2
+ import type { PluginOption } from 'vite';
3
3
  type Options = {
4
4
  /**
5
5
  * Control where the JSX factory is imported from.
@@ -18,7 +18,7 @@ type Options = {
18
18
  plugins?: [string, Record<string, any>][];
19
19
  /**
20
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://vitejs.dev/config/build-options.html#build-target
21
+ * For production target, see https://vite.dev/config/build-options.html#build-target
22
22
  * @default "es2020"
23
23
  */
24
24
  devTarget?: JscTarget;
@@ -29,6 +29,14 @@ type Options = {
29
29
  * Exclusion of node_modules should be handled by the function if needed.
30
30
  */
31
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;
32
40
  /**
33
41
  * The future of Vite is with OXC, and from the beginning this was a design choice
34
42
  * to not exposed too many specialties from SWC so that Vite React users can move to
package/index.mjs CHANGED
@@ -2,21 +2,121 @@
2
2
  import { readFileSync } from "fs";
3
3
  import { dirname, join } from "path";
4
4
  import { fileURLToPath } from "url";
5
+ import { createRequire } from "module";
5
6
  import {
6
7
  transform
7
8
  } from "@swc/core";
8
- import { createRequire } from "module";
9
+
10
+ // ../common/refresh-utils.ts
9
11
  var runtimePublicPath = "/@react-refresh";
10
- var preambleCode = `import { injectIntoGlobalHook } from "__PATH__";
12
+ var reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
13
+ var refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
14
+ var preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
15
+ 1
16
+ )}"
11
17
  injectIntoGlobalHook(window);
12
18
  window.$RefreshReg$ = () => {};
13
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")) {
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
14
116
  var _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
15
117
  var resolve = createRequire(
16
118
  typeof __filename !== "undefined" ? __filename : import.meta.url
17
119
  ).resolve;
18
- var reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
19
- var refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
20
120
  var react = (_options) => {
21
121
  let hmrDisabled = false;
22
122
  const options = {
@@ -25,6 +125,7 @@ var react = (_options) => {
25
125
  plugins: (_options == null ? void 0 : _options.plugins) ? _options == null ? void 0 : _options.plugins.map((el) => [resolve(el[0]), el[1]]) : void 0,
26
126
  devTarget: (_options == null ? void 0 : _options.devTarget) ?? "es2020",
27
127
  parserConfig: _options == null ? void 0 : _options.parserConfig,
128
+ reactRefreshHost: _options == null ? void 0 : _options.reactRefreshHost,
28
129
  useAtYourOwnRisk_mutateSwcOptions: _options == null ? void 0 : _options.useAtYourOwnRisk_mutateSwcOptions
29
130
  };
30
131
  return [
@@ -34,7 +135,10 @@ var react = (_options) => {
34
135
  enforce: "pre",
35
136
  // Run before Vite default resolve to avoid syscalls
36
137
  resolveId: (id) => id === runtimePublicPath ? id : void 0,
37
- load: (id) => id === runtimePublicPath ? readFileSync(join(_dirname, "refresh-runtime.js"), "utf-8") : void 0
138
+ load: (id) => id === runtimePublicPath ? readFileSync(join(_dirname, "refresh-runtime.js"), "utf-8").replace(
139
+ /__README_URL__/g,
140
+ "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc"
141
+ ) : void 0
38
142
  },
39
143
  {
40
144
  name: "vite:react-swc",
@@ -61,10 +165,7 @@ var react = (_options) => {
61
165
  {
62
166
  tag: "script",
63
167
  attrs: { type: "module" },
64
- children: preambleCode.replace(
65
- "__PATH__",
66
- config.server.config.base + runtimePublicPath.slice(1)
67
- )
168
+ children: getPreambleCode(config.server.config.base)
68
169
  }
69
170
  ],
70
171
  async transform(code, _id, transformOptions) {
@@ -84,38 +185,13 @@ var react = (_options) => {
84
185
  );
85
186
  if (!result) return;
86
187
  if (!refresh) return result;
87
- const hasRefresh = refreshContentRE.test(result.code);
88
- if (!hasRefresh && !reactCompRE.test(result.code)) return result;
89
- const sourceMap = JSON.parse(result.map);
90
- sourceMap.mappings = ";;" + sourceMap.mappings;
91
- result.code = `import * as RefreshRuntime from "${runtimePublicPath}";
92
-
93
- ${result.code}`;
94
- if (hasRefresh) {
95
- sourceMap.mappings = ";;;;;;" + sourceMap.mappings;
96
- result.code = `if (!window.$RefreshReg$) throw new Error("React refresh preamble was not loaded. Something is wrong.");
97
- const prevRefreshReg = window.$RefreshReg$;
98
- const prevRefreshSig = window.$RefreshSig$;
99
- window.$RefreshReg$ = RefreshRuntime.getRefreshReg("${id}");
100
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
101
-
102
- ${result.code}
103
-
104
- window.$RefreshReg$ = prevRefreshReg;
105
- window.$RefreshSig$ = prevRefreshSig;
106
- `;
107
- }
108
- result.code += `
109
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
110
- RefreshRuntime.registerExportsForReactRefresh("${id}", currentExports);
111
- import.meta.hot.accept((nextExports) => {
112
- if (!nextExports) return;
113
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate("${id}", currentExports, nextExports);
114
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
115
- });
116
- });
117
- `;
118
- return { code: result.code, map: sourceMap };
188
+ return addRefreshWrapper(
189
+ result.code,
190
+ result.map,
191
+ "@vitejs/plugin-react-swc",
192
+ id,
193
+ options.reactRefreshHost
194
+ );
119
195
  }
120
196
  },
121
197
  options.plugins ? {
@@ -178,7 +254,7 @@ var transformWithOptions = async (id, code, target, options, reactConfig) => {
178
254
  const message = e.message;
179
255
  const fileStartIndex = message.indexOf("\u256D\u2500[");
180
256
  if (fileStartIndex !== -1) {
181
- const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)]/);
257
+ const match = message.slice(fileStartIndex).match(/:(\d+):(\d+)\]/);
182
258
  if (match) {
183
259
  e.line = match[1];
184
260
  e.column = match[2];
@@ -188,24 +264,6 @@ var transformWithOptions = async (id, code, target, options, reactConfig) => {
188
264
  }
189
265
  return result;
190
266
  };
191
- var silenceUseClientWarning = (userConfig) => ({
192
- rollupOptions: {
193
- onwarn(warning, defaultHandler) {
194
- var _a, _b;
195
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
196
- return;
197
- }
198
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
199
- return;
200
- }
201
- if ((_b = (_a = userConfig.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.onwarn) {
202
- userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
203
- } else {
204
- defaultHandler(warning);
205
- }
206
- }
207
- }
208
- });
209
267
  var index_default = react;
210
268
  export {
211
269
  index_default as default
package/package.json CHANGED
@@ -1,21 +1,9 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-react-swc",
3
- "description": "Speed up your Vite dev server with SWC",
4
- "version": "3.8.1",
5
- "author": "Arnaud Barré (https://github.com/ArnaudBarre)",
3
+ "version": "3.9.0-beta.3",
6
4
  "license": "MIT",
7
- "repository": "github:vitejs/vite-plugin-react-swc",
8
- "type": "module",
9
- "main": "index.cjs",
10
- "types": "index.d.ts",
11
- "module": "index.mjs",
12
- "exports": {
13
- ".": {
14
- "types": "./index.d.ts",
15
- "require": "./index.cjs",
16
- "import": "./index.mjs"
17
- }
18
- },
5
+ "author": "Arnaud Barré (https://github.com/ArnaudBarre)",
6
+ "description": "Speed up your Vite dev server with SWC",
19
7
  "keywords": [
20
8
  "vite",
21
9
  "vite-plugin",
@@ -24,10 +12,30 @@
24
12
  "react-refresh",
25
13
  "fast refresh"
26
14
  ],
15
+ "type": "module",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/vitejs/vite-plugin-react.git",
19
+ "directory": "packages/plugin-react-swc"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/vitejs/vite-plugin-react/issues"
23
+ },
24
+ "homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc#readme",
25
+ "dependencies": {
26
+ "@swc/core": "^1.11.21"
27
+ },
27
28
  "peerDependencies": {
28
29
  "vite": "^4 || ^5 || ^6"
29
30
  },
30
- "dependencies": {
31
- "@swc/core": "^1.11.11"
31
+ "main": "index.cjs",
32
+ "types": "index.d.ts",
33
+ "module": "index.mjs",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./index.d.ts",
37
+ "require": "./index.cjs",
38
+ "import": "./index.mjs"
39
+ }
32
40
  }
33
41
  }
@@ -421,7 +421,7 @@ function validateRefreshBoundaryAndEnqueueUpdate(id, prevExports, nextExports) {
421
421
  if (hasExports && allExportsAreComponentsOrUnchanged === true) {
422
422
  enqueueUpdate();
423
423
  } else {
424
- return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at https://github.com/vitejs/vite-plugin-react-swc#consistent-components-exports`;
424
+ return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`;
425
425
  }
426
426
  }
427
427
  function predicateOnExport(ignoredExports, moduleExports, predicate) {