@vitejs/plugin-react 2.2.0 → 3.0.0-alpha.1

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/dist/index.cjs CHANGED
@@ -69,7 +69,7 @@ if (import.meta.hot) {
69
69
  RefreshRuntime.register(type, __SOURCE__ + " " + id)
70
70
  };
71
71
  window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
72
- }`.replace(/[\n]+/gm, "");
72
+ }`.replace(/\n+/g, "");
73
73
  const timeout = `
74
74
  if (!window.__vite_plugin_react_timeout) {
75
75
  window.__vite_plugin_react_timeout = setTimeout(() => {
@@ -151,83 +151,9 @@ function isComponentLikeName(name) {
151
151
  return typeof name === "string" && name[0] >= "A" && name[0] <= "Z";
152
152
  }
153
153
 
154
- function babelImportToRequire({ types: t }) {
155
- return {
156
- visitor: {
157
- ImportDeclaration(path) {
158
- const decl = path.node;
159
- const spec = decl.specifiers[0];
160
- path.replaceWith(
161
- t.variableDeclaration("var", [
162
- t.variableDeclarator(
163
- spec.local,
164
- t.memberExpression(
165
- t.callExpression(t.identifier("require"), [decl.source]),
166
- spec.imported
167
- )
168
- )
169
- ])
170
- );
171
- }
172
- }
173
- };
174
- }
175
-
176
- let babelRestoreJSX;
177
- const jsxNotFound = [null, false];
178
- async function getBabelRestoreJSX() {
179
- if (!babelRestoreJSX)
180
- babelRestoreJSX = import('./chunks/babel-restore-jsx.cjs').then((r) => {
181
- const fn = r.default;
182
- if ("default" in fn)
183
- return fn.default;
184
- return fn;
185
- });
186
- return babelRestoreJSX;
187
- }
188
- async function restoreJSX(babel, code, filename) {
189
- const [reactAlias, isCommonJS] = parseReactAlias(code);
190
- if (!reactAlias) {
191
- return jsxNotFound;
192
- }
193
- const reactJsxRE = new RegExp(
194
- `\\b${reactAlias}\\.(createElement|Fragment)\\b`,
195
- "g"
196
- );
197
- if (!reactJsxRE.test(code)) {
198
- return jsxNotFound;
199
- }
200
- const result = await babel.transformAsync(code, {
201
- babelrc: false,
202
- configFile: false,
203
- ast: true,
204
- code: false,
205
- filename,
206
- parserOpts: {
207
- plugins: ["jsx"]
208
- },
209
- plugins: [[await getBabelRestoreJSX(), { reactAlias }]]
210
- });
211
- return [result?.ast, isCommonJS];
212
- }
213
- function parseReactAlias(code) {
214
- let match = code.match(
215
- /\b(var|let|const)\s+([^=\{\s]+)\s*=\s*require\(["']react["']\)/
216
- );
217
- if (match) {
218
- return [match[2], true];
219
- }
220
- match = code.match(/^import\s+(?:\*\s+as\s+)?(\w+).+?\bfrom\s*["']react["']/m);
221
- if (match) {
222
- return [match[1], false];
223
- }
224
- return [void 0, false];
225
- }
226
-
227
154
  const prependReactImportCode = "import React from 'react'; ";
228
155
  function viteReact(opts = {}) {
229
156
  let devBase = "/";
230
- let resolvedCacheDir;
231
157
  let filter = vite.createFilter(opts.include, opts.exclude);
232
158
  let needHiresSourcemap = false;
233
159
  let isProduction = true;
@@ -237,18 +163,36 @@ function viteReact(opts = {}) {
237
163
  let runPluginOverrides = (options, context) => false;
238
164
  let staticBabelOptions;
239
165
  const useAutomaticRuntime = opts.jsxRuntime !== "classic";
240
- const importReactRE = /(^|\n)import\s+(\*\s+as\s+)?React(,|\s+)/;
241
- const fileExtensionRE = /\.[^\/\s\?]+$/;
166
+ const importReactRE = /(?:^|\n)import\s+(?:\*\s+as\s+)?React(?:,|\s+)/;
167
+ const fileExtensionRE = /\.[^/\s?]+$/;
242
168
  const viteBabel = {
243
169
  name: "vite:react-babel",
244
170
  enforce: "pre",
245
- config() {
171
+ config(userConfig, { mode }) {
172
+ const resolvedRoot = vite.normalizePath(
173
+ userConfig.root ? path.resolve(userConfig.root) : process.cwd()
174
+ );
175
+ const envDir = userConfig.envDir ? vite.normalizePath(path.resolve(resolvedRoot, userConfig.envDir)) : resolvedRoot;
176
+ vite.loadEnv(mode, envDir, vite.resolveEnvPrefix(userConfig));
177
+ const isProduction2 = (process.env.NODE_ENV || process.env.VITE_USER_NODE_ENV || mode) === "production";
246
178
  if (opts.jsxRuntime === "classic") {
247
179
  return {
248
180
  esbuild: {
249
181
  logOverride: {
250
182
  "this-is-undefined-in-esm": "silent"
251
- }
183
+ },
184
+ jsx: "transform",
185
+ jsxImportSource: opts.jsxImportSource,
186
+ jsxSideEffects: opts.jsxPure === false
187
+ }
188
+ };
189
+ } else {
190
+ return {
191
+ esbuild: {
192
+ jsxDev: !isProduction2,
193
+ jsx: "automatic",
194
+ jsxImportSource: opts.jsxImportSource,
195
+ jsxSideEffects: opts.jsxPure === false
252
196
  }
253
197
  };
254
198
  }
@@ -256,7 +200,6 @@ function viteReact(opts = {}) {
256
200
  configResolved(config) {
257
201
  devBase = config.base;
258
202
  projectRoot = config.root;
259
- resolvedCacheDir = vite.normalizePath(path.resolve(config.cacheDir));
260
203
  filter = vite.createFilter(opts.include, opts.exclude, {
261
204
  resolve: projectRoot
262
205
  });
@@ -293,7 +236,7 @@ function viteReact(opts = {}) {
293
236
  const ssr = options?.ssr === true;
294
237
  const [filepath, querystring = ""] = id.split("?");
295
238
  const [extension = ""] = querystring.match(fileExtensionRE) || filepath.match(fileExtensionRE) || [];
296
- if (/\.(mjs|[tj]sx?)$/.test(extension)) {
239
+ if (/\.(?:mjs|[tj]sx?)$/.test(extension)) {
297
240
  const isJSX = extension.endsWith("x");
298
241
  const isNodeModules = id.includes("/node_modules/");
299
242
  const isProjectFile = !isNodeModules && (id[0] === "\0" || id.startsWith(projectRoot + "/"));
@@ -320,29 +263,9 @@ function viteReact(opts = {}) {
320
263
  ]);
321
264
  }
322
265
  }
323
- let ast;
324
266
  let prependReactImport = false;
325
267
  if (!isProjectFile || isJSX) {
326
- if (useAutomaticRuntime) {
327
- const isOptimizedReactDom = id.startsWith(resolvedCacheDir) && id.includes("/react-dom.js");
328
- const [restoredAst, isCommonJS] = !isProjectFile && !isJSX && !isOptimizedReactDom ? await restoreJSX(babel__namespace, code, id) : [null, false];
329
- if (isJSX || (ast = restoredAst)) {
330
- plugins.push([
331
- await loadPlugin(
332
- "@babel/plugin-transform-react-jsx" + (isProduction ? "" : "-development")
333
- ),
334
- {
335
- runtime: "automatic",
336
- importSource: opts.jsxImportSource,
337
- pure: opts.jsxPure !== false,
338
- throwIfNamespace: opts.jsxThrowIfNamespace
339
- }
340
- ]);
341
- if (isCommonJS) {
342
- plugins.push(babelImportToRequire);
343
- }
344
- }
345
- } else if (isProjectFile) {
268
+ if (!useAutomaticRuntime && isProjectFile) {
346
269
  if (!isProduction) {
347
270
  plugins.push(
348
271
  await loadPlugin("@babel/plugin-transform-react-jsx-self"),
@@ -386,7 +309,7 @@ function viteReact(opts = {}) {
386
309
  if (/\.tsx?$/.test(extension)) {
387
310
  parserPlugins.push("typescript");
388
311
  }
389
- const transformAsync = ast ? babel__namespace.transformFromAstAsync.bind(babel__namespace, ast, code) : babel__namespace.transformAsync.bind(babel__namespace, code);
312
+ const transformAsync = babel__namespace.transformAsync.bind(babel__namespace, code);
390
313
  const isReasonReact = extension.endsWith(".bs.js");
391
314
  const result = await transformAsync({
392
315
  ...babelOptions,
package/dist/index.d.ts CHANGED
@@ -26,11 +26,6 @@ interface Options {
26
26
  * @default true
27
27
  */
28
28
  jsxPure?: boolean;
29
- /**
30
- * Toggles whether or not to throw an error if an XML namespaced tag name is used.
31
- * @default true
32
- */
33
- jsxThrowIfNamespace?: boolean;
34
29
  /**
35
30
  * Babel configuration applied in both dev and prod.
36
31
  */
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import * as babel from '@babel/core';
3
- import { createFilter, normalizePath } from 'vite';
3
+ import { createFilter, normalizePath, loadEnv, resolveEnvPrefix } from 'vite';
4
4
  import MagicString from 'magic-string';
5
5
  import fs from 'node:fs';
6
6
  import { createRequire } from 'node:module';
@@ -54,7 +54,7 @@ if (import.meta.hot) {
54
54
  RefreshRuntime.register(type, __SOURCE__ + " " + id)
55
55
  };
56
56
  window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
57
- }`.replace(/[\n]+/gm, "");
57
+ }`.replace(/\n+/g, "");
58
58
  const timeout = `
59
59
  if (!window.__vite_plugin_react_timeout) {
60
60
  window.__vite_plugin_react_timeout = setTimeout(() => {
@@ -136,83 +136,9 @@ function isComponentLikeName(name) {
136
136
  return typeof name === "string" && name[0] >= "A" && name[0] <= "Z";
137
137
  }
138
138
 
139
- function babelImportToRequire({ types: t }) {
140
- return {
141
- visitor: {
142
- ImportDeclaration(path) {
143
- const decl = path.node;
144
- const spec = decl.specifiers[0];
145
- path.replaceWith(
146
- t.variableDeclaration("var", [
147
- t.variableDeclarator(
148
- spec.local,
149
- t.memberExpression(
150
- t.callExpression(t.identifier("require"), [decl.source]),
151
- spec.imported
152
- )
153
- )
154
- ])
155
- );
156
- }
157
- }
158
- };
159
- }
160
-
161
- let babelRestoreJSX;
162
- const jsxNotFound = [null, false];
163
- async function getBabelRestoreJSX() {
164
- if (!babelRestoreJSX)
165
- babelRestoreJSX = import('./chunks/babel-restore-jsx.mjs').then((r) => {
166
- const fn = r.default;
167
- if ("default" in fn)
168
- return fn.default;
169
- return fn;
170
- });
171
- return babelRestoreJSX;
172
- }
173
- async function restoreJSX(babel, code, filename) {
174
- const [reactAlias, isCommonJS] = parseReactAlias(code);
175
- if (!reactAlias) {
176
- return jsxNotFound;
177
- }
178
- const reactJsxRE = new RegExp(
179
- `\\b${reactAlias}\\.(createElement|Fragment)\\b`,
180
- "g"
181
- );
182
- if (!reactJsxRE.test(code)) {
183
- return jsxNotFound;
184
- }
185
- const result = await babel.transformAsync(code, {
186
- babelrc: false,
187
- configFile: false,
188
- ast: true,
189
- code: false,
190
- filename,
191
- parserOpts: {
192
- plugins: ["jsx"]
193
- },
194
- plugins: [[await getBabelRestoreJSX(), { reactAlias }]]
195
- });
196
- return [result?.ast, isCommonJS];
197
- }
198
- function parseReactAlias(code) {
199
- let match = code.match(
200
- /\b(var|let|const)\s+([^=\{\s]+)\s*=\s*require\(["']react["']\)/
201
- );
202
- if (match) {
203
- return [match[2], true];
204
- }
205
- match = code.match(/^import\s+(?:\*\s+as\s+)?(\w+).+?\bfrom\s*["']react["']/m);
206
- if (match) {
207
- return [match[1], false];
208
- }
209
- return [void 0, false];
210
- }
211
-
212
139
  const prependReactImportCode = "import React from 'react'; ";
213
140
  function viteReact(opts = {}) {
214
141
  let devBase = "/";
215
- let resolvedCacheDir;
216
142
  let filter = createFilter(opts.include, opts.exclude);
217
143
  let needHiresSourcemap = false;
218
144
  let isProduction = true;
@@ -222,18 +148,36 @@ function viteReact(opts = {}) {
222
148
  let runPluginOverrides = (options, context) => false;
223
149
  let staticBabelOptions;
224
150
  const useAutomaticRuntime = opts.jsxRuntime !== "classic";
225
- const importReactRE = /(^|\n)import\s+(\*\s+as\s+)?React(,|\s+)/;
226
- const fileExtensionRE = /\.[^\/\s\?]+$/;
151
+ const importReactRE = /(?:^|\n)import\s+(?:\*\s+as\s+)?React(?:,|\s+)/;
152
+ const fileExtensionRE = /\.[^/\s?]+$/;
227
153
  const viteBabel = {
228
154
  name: "vite:react-babel",
229
155
  enforce: "pre",
230
- config() {
156
+ config(userConfig, { mode }) {
157
+ const resolvedRoot = normalizePath(
158
+ userConfig.root ? path.resolve(userConfig.root) : process.cwd()
159
+ );
160
+ const envDir = userConfig.envDir ? normalizePath(path.resolve(resolvedRoot, userConfig.envDir)) : resolvedRoot;
161
+ loadEnv(mode, envDir, resolveEnvPrefix(userConfig));
162
+ const isProduction2 = (process.env.NODE_ENV || process.env.VITE_USER_NODE_ENV || mode) === "production";
231
163
  if (opts.jsxRuntime === "classic") {
232
164
  return {
233
165
  esbuild: {
234
166
  logOverride: {
235
167
  "this-is-undefined-in-esm": "silent"
236
- }
168
+ },
169
+ jsx: "transform",
170
+ jsxImportSource: opts.jsxImportSource,
171
+ jsxSideEffects: opts.jsxPure === false
172
+ }
173
+ };
174
+ } else {
175
+ return {
176
+ esbuild: {
177
+ jsxDev: !isProduction2,
178
+ jsx: "automatic",
179
+ jsxImportSource: opts.jsxImportSource,
180
+ jsxSideEffects: opts.jsxPure === false
237
181
  }
238
182
  };
239
183
  }
@@ -241,7 +185,6 @@ function viteReact(opts = {}) {
241
185
  configResolved(config) {
242
186
  devBase = config.base;
243
187
  projectRoot = config.root;
244
- resolvedCacheDir = normalizePath(path.resolve(config.cacheDir));
245
188
  filter = createFilter(opts.include, opts.exclude, {
246
189
  resolve: projectRoot
247
190
  });
@@ -278,7 +221,7 @@ function viteReact(opts = {}) {
278
221
  const ssr = options?.ssr === true;
279
222
  const [filepath, querystring = ""] = id.split("?");
280
223
  const [extension = ""] = querystring.match(fileExtensionRE) || filepath.match(fileExtensionRE) || [];
281
- if (/\.(mjs|[tj]sx?)$/.test(extension)) {
224
+ if (/\.(?:mjs|[tj]sx?)$/.test(extension)) {
282
225
  const isJSX = extension.endsWith("x");
283
226
  const isNodeModules = id.includes("/node_modules/");
284
227
  const isProjectFile = !isNodeModules && (id[0] === "\0" || id.startsWith(projectRoot + "/"));
@@ -305,29 +248,9 @@ function viteReact(opts = {}) {
305
248
  ]);
306
249
  }
307
250
  }
308
- let ast;
309
251
  let prependReactImport = false;
310
252
  if (!isProjectFile || isJSX) {
311
- if (useAutomaticRuntime) {
312
- const isOptimizedReactDom = id.startsWith(resolvedCacheDir) && id.includes("/react-dom.js");
313
- const [restoredAst, isCommonJS] = !isProjectFile && !isJSX && !isOptimizedReactDom ? await restoreJSX(babel, code, id) : [null, false];
314
- if (isJSX || (ast = restoredAst)) {
315
- plugins.push([
316
- await loadPlugin(
317
- "@babel/plugin-transform-react-jsx" + (isProduction ? "" : "-development")
318
- ),
319
- {
320
- runtime: "automatic",
321
- importSource: opts.jsxImportSource,
322
- pure: opts.jsxPure !== false,
323
- throwIfNamespace: opts.jsxThrowIfNamespace
324
- }
325
- ]);
326
- if (isCommonJS) {
327
- plugins.push(babelImportToRequire);
328
- }
329
- }
330
- } else if (isProjectFile) {
253
+ if (!useAutomaticRuntime && isProjectFile) {
331
254
  if (!isProduction) {
332
255
  plugins.push(
333
256
  await loadPlugin("@babel/plugin-transform-react-jsx-self"),
@@ -371,7 +294,7 @@ function viteReact(opts = {}) {
371
294
  if (/\.tsx?$/.test(extension)) {
372
295
  parserPlugins.push("typescript");
373
296
  }
374
- const transformAsync = ast ? babel.transformFromAstAsync.bind(babel, ast, code) : babel.transformAsync.bind(babel, code);
297
+ const transformAsync = babel.transformAsync.bind(babel, code);
375
298
  const isReasonReact = extension.endsWith(".bs.js");
376
299
  const result = await transformAsync({
377
300
  ...babelOptions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-react",
3
- "version": "2.2.0",
3
+ "version": "3.0.0-alpha.1",
4
4
  "license": "MIT",
5
5
  "author": "Evan You",
6
6
  "contributors": [
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-react#readme",
40
40
  "dependencies": {
41
- "@babel/core": "^7.19.6",
41
+ "@babel/core": "^7.20.2",
42
42
  "@babel/plugin-transform-react-jsx": "^7.19.0",
43
43
  "@babel/plugin-transform-react-jsx-development": "^7.18.6",
44
44
  "@babel/plugin-transform-react-jsx-self": "^7.18.6",
@@ -1,138 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * https://github.com/flying-sheep/babel-plugin-transform-react-createelement-to-jsx
5
- * @license GNU General Public License v3.0
6
- */
7
- function babelRestoreJsx({ types: t }, { reactAlias = "React" }) {
8
- function getJSXNode(node) {
9
- if (!isReactCreateElement(node)) {
10
- return null;
11
- }
12
- const [nameNode, propsNode, ...childNodes] = node.arguments;
13
- const name = getJSXName(nameNode);
14
- if (name == null) {
15
- return null;
16
- }
17
- const props = getJSXProps(propsNode);
18
- if (props == null) {
19
- return null;
20
- }
21
- const children = getJSXChildren(childNodes);
22
- if (children == null) {
23
- return null;
24
- }
25
- if (t.isJSXMemberExpression(name) && t.isJSXIdentifier(name.object) && name.object.name === reactAlias && name.property.name === "Fragment") {
26
- return t.jsxFragment(
27
- t.jsxOpeningFragment(),
28
- t.jsxClosingFragment(),
29
- children
30
- );
31
- }
32
- const selfClosing = children.length === 0;
33
- const startTag = t.jsxOpeningElement(name, props, selfClosing);
34
- startTag.loc = node.loc;
35
- const endTag = selfClosing ? null : t.jsxClosingElement(name);
36
- return t.jsxElement(startTag, endTag, children, selfClosing);
37
- }
38
- function getJSXName(node) {
39
- if (node == null) {
40
- return null;
41
- }
42
- const name = getJSXIdentifier(node, true);
43
- if (name != null) {
44
- return name;
45
- }
46
- if (!t.isMemberExpression(node)) {
47
- return null;
48
- }
49
- const object = getJSXName(node.object);
50
- const property = getJSXName(node.property);
51
- if (object == null || property == null) {
52
- return null;
53
- }
54
- return t.jsxMemberExpression(object, property);
55
- }
56
- function getJSXProps(node) {
57
- if (node == null || isNullLikeNode(node)) {
58
- return [];
59
- }
60
- if (t.isCallExpression(node) && t.isIdentifier(node.callee, { name: "_extends" })) {
61
- const props = node.arguments.map(getJSXProps);
62
- if (props.every((prop) => prop != null)) {
63
- return [].concat(...props);
64
- }
65
- }
66
- if (!t.isObjectExpression(node) && t.isExpression(node))
67
- return [t.jsxSpreadAttribute(node)];
68
- if (!isPlainObjectExpression(node)) {
69
- return null;
70
- }
71
- return node.properties.map(
72
- (prop) => t.isObjectProperty(prop) ? t.jsxAttribute(
73
- getJSXIdentifier(prop.key),
74
- getJSXAttributeValue(prop.value)
75
- ) : t.jsxSpreadAttribute(prop.argument)
76
- ).filter(
77
- (prop) => t.isJSXIdentifier(prop.name) ? prop.name.name !== "__self" && prop.name.name !== "__source" : true
78
- );
79
- }
80
- function getJSXChild(node) {
81
- if (t.isStringLiteral(node)) {
82
- return t.jsxText(node.value);
83
- }
84
- if (isReactCreateElement(node)) {
85
- return getJSXNode(node);
86
- }
87
- if (t.isExpression(node)) {
88
- return t.jsxExpressionContainer(node);
89
- }
90
- return null;
91
- }
92
- function getJSXChildren(nodes) {
93
- const children = nodes.filter((node) => !isNullLikeNode(node)).map(getJSXChild);
94
- if (children.some((child) => child == null)) {
95
- return null;
96
- }
97
- return children;
98
- }
99
- function getJSXIdentifier(node, tag = false) {
100
- if (t.isIdentifier(node) && (!tag || node.name.match(/^[A-Z]/))) {
101
- return t.jsxIdentifier(node.name);
102
- }
103
- if (t.isStringLiteral(node)) {
104
- return t.jsxIdentifier(node.value);
105
- }
106
- return null;
107
- }
108
- function getJSXAttributeValue(node) {
109
- if (t.isStringLiteral(node)) {
110
- return node;
111
- }
112
- if (t.isJSXElement(node)) {
113
- return node;
114
- }
115
- if (t.isExpression(node)) {
116
- return t.jsxExpressionContainer(node);
117
- }
118
- return null;
119
- }
120
- const isReactCreateElement = (node) => t.isCallExpression(node) && t.isMemberExpression(node.callee) && t.isIdentifier(node.callee.object, { name: reactAlias }) && t.isIdentifier(node.callee.property, { name: "createElement" }) && !node.callee.computed;
121
- const isNullLikeNode = (node) => t.isNullLiteral(node) || t.isIdentifier(node, { name: "undefined" });
122
- const isPlainObjectExpression = (node) => t.isObjectExpression(node) && node.properties.every(
123
- (property) => t.isSpreadElement(property) || t.isObjectProperty(property, { computed: false }) && getJSXIdentifier(property.key) != null && getJSXAttributeValue(property.value) != null
124
- );
125
- return {
126
- visitor: {
127
- CallExpression(path) {
128
- const node = getJSXNode(path.node);
129
- if (node == null) {
130
- return null;
131
- }
132
- path.replaceWith(node);
133
- }
134
- }
135
- };
136
- }
137
-
138
- exports.default = babelRestoreJsx;
@@ -1,136 +0,0 @@
1
- /**
2
- * https://github.com/flying-sheep/babel-plugin-transform-react-createelement-to-jsx
3
- * @license GNU General Public License v3.0
4
- */
5
- function babelRestoreJsx({ types: t }, { reactAlias = "React" }) {
6
- function getJSXNode(node) {
7
- if (!isReactCreateElement(node)) {
8
- return null;
9
- }
10
- const [nameNode, propsNode, ...childNodes] = node.arguments;
11
- const name = getJSXName(nameNode);
12
- if (name == null) {
13
- return null;
14
- }
15
- const props = getJSXProps(propsNode);
16
- if (props == null) {
17
- return null;
18
- }
19
- const children = getJSXChildren(childNodes);
20
- if (children == null) {
21
- return null;
22
- }
23
- if (t.isJSXMemberExpression(name) && t.isJSXIdentifier(name.object) && name.object.name === reactAlias && name.property.name === "Fragment") {
24
- return t.jsxFragment(
25
- t.jsxOpeningFragment(),
26
- t.jsxClosingFragment(),
27
- children
28
- );
29
- }
30
- const selfClosing = children.length === 0;
31
- const startTag = t.jsxOpeningElement(name, props, selfClosing);
32
- startTag.loc = node.loc;
33
- const endTag = selfClosing ? null : t.jsxClosingElement(name);
34
- return t.jsxElement(startTag, endTag, children, selfClosing);
35
- }
36
- function getJSXName(node) {
37
- if (node == null) {
38
- return null;
39
- }
40
- const name = getJSXIdentifier(node, true);
41
- if (name != null) {
42
- return name;
43
- }
44
- if (!t.isMemberExpression(node)) {
45
- return null;
46
- }
47
- const object = getJSXName(node.object);
48
- const property = getJSXName(node.property);
49
- if (object == null || property == null) {
50
- return null;
51
- }
52
- return t.jsxMemberExpression(object, property);
53
- }
54
- function getJSXProps(node) {
55
- if (node == null || isNullLikeNode(node)) {
56
- return [];
57
- }
58
- if (t.isCallExpression(node) && t.isIdentifier(node.callee, { name: "_extends" })) {
59
- const props = node.arguments.map(getJSXProps);
60
- if (props.every((prop) => prop != null)) {
61
- return [].concat(...props);
62
- }
63
- }
64
- if (!t.isObjectExpression(node) && t.isExpression(node))
65
- return [t.jsxSpreadAttribute(node)];
66
- if (!isPlainObjectExpression(node)) {
67
- return null;
68
- }
69
- return node.properties.map(
70
- (prop) => t.isObjectProperty(prop) ? t.jsxAttribute(
71
- getJSXIdentifier(prop.key),
72
- getJSXAttributeValue(prop.value)
73
- ) : t.jsxSpreadAttribute(prop.argument)
74
- ).filter(
75
- (prop) => t.isJSXIdentifier(prop.name) ? prop.name.name !== "__self" && prop.name.name !== "__source" : true
76
- );
77
- }
78
- function getJSXChild(node) {
79
- if (t.isStringLiteral(node)) {
80
- return t.jsxText(node.value);
81
- }
82
- if (isReactCreateElement(node)) {
83
- return getJSXNode(node);
84
- }
85
- if (t.isExpression(node)) {
86
- return t.jsxExpressionContainer(node);
87
- }
88
- return null;
89
- }
90
- function getJSXChildren(nodes) {
91
- const children = nodes.filter((node) => !isNullLikeNode(node)).map(getJSXChild);
92
- if (children.some((child) => child == null)) {
93
- return null;
94
- }
95
- return children;
96
- }
97
- function getJSXIdentifier(node, tag = false) {
98
- if (t.isIdentifier(node) && (!tag || node.name.match(/^[A-Z]/))) {
99
- return t.jsxIdentifier(node.name);
100
- }
101
- if (t.isStringLiteral(node)) {
102
- return t.jsxIdentifier(node.value);
103
- }
104
- return null;
105
- }
106
- function getJSXAttributeValue(node) {
107
- if (t.isStringLiteral(node)) {
108
- return node;
109
- }
110
- if (t.isJSXElement(node)) {
111
- return node;
112
- }
113
- if (t.isExpression(node)) {
114
- return t.jsxExpressionContainer(node);
115
- }
116
- return null;
117
- }
118
- const isReactCreateElement = (node) => t.isCallExpression(node) && t.isMemberExpression(node.callee) && t.isIdentifier(node.callee.object, { name: reactAlias }) && t.isIdentifier(node.callee.property, { name: "createElement" }) && !node.callee.computed;
119
- const isNullLikeNode = (node) => t.isNullLiteral(node) || t.isIdentifier(node, { name: "undefined" });
120
- const isPlainObjectExpression = (node) => t.isObjectExpression(node) && node.properties.every(
121
- (property) => t.isSpreadElement(property) || t.isObjectProperty(property, { computed: false }) && getJSXIdentifier(property.key) != null && getJSXAttributeValue(property.value) != null
122
- );
123
- return {
124
- visitor: {
125
- CallExpression(path) {
126
- const node = getJSXNode(path.node);
127
- if (node == null) {
128
- return null;
129
- }
130
- path.replaceWith(node);
131
- }
132
- }
133
- };
134
- }
135
-
136
- export { babelRestoreJsx as default };