@vitejs/plugin-react 1.1.3 → 1.3.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/README.md CHANGED
@@ -33,6 +33,16 @@ react({
33
33
  })
34
34
  ```
35
35
 
36
+ ## Opting out of the automatic JSX runtime
37
+
38
+ By default, the plugin uses the [automatic JSX runtime](https://github.com/alloc/vite-react-jsx#faq). However, if you encounter any issues, you may opt out using the `jsxRuntime` option.
39
+
40
+ ```js
41
+ react({
42
+ jsxRuntime: 'classic'
43
+ })
44
+ ```
45
+
36
46
  ## Babel configuration
37
47
 
38
48
  The `babel` option lets you add plugins, presets, and [other configuration](https://babeljs.io/docs/en/options) to the Babel transformation performed on each JSX/TSX file.
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ import type { ParserOptions } from '@babel/core';
2
2
  import type { PluginOption } from 'vite';
3
3
  import type { TransformOptions } from '@babel/core';
4
4
 
5
+ export declare type BabelOptions = Omit<TransformOptions, 'ast' | 'filename' | 'root' | 'sourceFileName' | 'sourceMaps' | 'inputSourceMap'>;
6
+
5
7
  export declare interface Options {
6
8
  include?: string | RegExp | Array<string | RegExp>;
7
9
  exclude?: string | RegExp | Array<string | RegExp>;
@@ -21,16 +23,35 @@ export declare interface Options {
21
23
  * @default "react"
22
24
  */
23
25
  jsxImportSource?: string;
26
+ /**
27
+ * Set this to `true` to annotate the JSX factory with `\/* @__PURE__ *\/`.
28
+ * This option is ignored when `jsxRuntime` is not `"automatic"`.
29
+ * @default true
30
+ */
31
+ jsxPure?: boolean;
24
32
  /**
25
33
  * Babel configuration applied in both dev and prod.
26
34
  */
27
- babel?: TransformOptions;
35
+ babel?: BabelOptions;
28
36
  /**
29
37
  * @deprecated Use `babel.parserOpts.plugins` instead
30
38
  */
31
39
  parserPlugins?: ParserOptions['plugins'];
32
40
  }
33
41
 
42
+ /**
43
+ * The object type used by the `options` passed to plugins with
44
+ * an `api.reactBabel` method.
45
+ */
46
+ export declare interface ReactBabelOptions extends BabelOptions {
47
+ plugins: Extract<BabelOptions['plugins'], any[]>;
48
+ presets: Extract<BabelOptions['presets'], any[]>;
49
+ overrides: Extract<BabelOptions['overrides'], any[]>;
50
+ parserOpts: ParserOptions & {
51
+ plugins: Extract<ParserOptions['plugins'], any[]>;
52
+ };
53
+ }
54
+
34
55
  declare function viteReact(opts?: Options): PluginOption[];
35
56
 
36
57
  declare namespace viteReact {
package/dist/index.js CHANGED
@@ -21,26 +21,23 @@ var __spreadValues = (a, b) => {
21
21
  return a;
22
22
  };
23
23
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
- var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25
24
  var __esm = (fn, res) => function __init() {
26
- return fn && (res = (0, fn[Object.keys(fn)[0]])(fn = 0)), res;
25
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
27
26
  };
28
27
  var __export = (target, all) => {
29
- __markAsModule(target);
30
28
  for (var name in all)
31
29
  __defProp(target, name, { get: all[name], enumerable: true });
32
30
  };
33
- var __reExport = (target, module2, desc) => {
34
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
35
- for (let key of __getOwnPropNames(module2))
36
- if (!__hasOwnProp.call(target, key) && key !== "default")
37
- __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
31
+ var __copyProps = (to, from, except, desc) => {
32
+ if (from && typeof from === "object" || typeof from === "function") {
33
+ for (let key of __getOwnPropNames(from))
34
+ if (!__hasOwnProp.call(to, key) && key !== except)
35
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
38
36
  }
39
- return target;
40
- };
41
- var __toModule = (module2) => {
42
- return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
37
+ return to;
43
38
  };
39
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
40
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
44
41
 
45
42
  // src/jsx-runtime/babel-restore-jsx.ts
46
43
  var babel_restore_jsx_exports = {};
@@ -78,7 +75,7 @@ function babel_restore_jsx_default({ types: t }) {
78
75
  if (node == null) {
79
76
  return null;
80
77
  }
81
- const name = getJSXIdentifier(node);
78
+ const name = getJSXIdentifier(node, true);
82
79
  if (name != null) {
83
80
  return name;
84
81
  }
@@ -128,8 +125,8 @@ function babel_restore_jsx_default({ types: t }) {
128
125
  }
129
126
  return children;
130
127
  }
131
- function getJSXIdentifier(node) {
132
- if (t.isIdentifier(node)) {
128
+ function getJSXIdentifier(node, tag = false) {
129
+ if (t.isIdentifier(node) && (!tag || node.name.match(/^[A-Z]/))) {
133
130
  return t.jsxIdentifier(node.name);
134
131
  }
135
132
  if (t.isStringLiteral(node)) {
@@ -170,15 +167,18 @@ var init_babel_restore_jsx = __esm({
170
167
  });
171
168
 
172
169
  // src/index.ts
173
- __export(exports, {
170
+ var src_exports = {};
171
+ __export(src_exports, {
174
172
  default: () => viteReact
175
173
  });
176
- var babel = __toModule(require("@babel/core"));
177
- var import_pluginutils = __toModule(require("@rollup/pluginutils"));
178
- var import_resolve = __toModule(require("resolve"));
174
+ module.exports = viteReact;
175
+ viteReact['default'] = viteReact;
176
+ var babel = __toESM(require("@babel/core"));
177
+ var import_pluginutils = require("@rollup/pluginutils");
178
+ var import_resolve = __toESM(require("resolve"));
179
179
 
180
180
  // src/fast-refresh.ts
181
- var import_fs = __toModule(require("fs"));
181
+ var import_fs = __toESM(require("fs"));
182
182
  var runtimePublicPath = "/@react-refresh";
183
183
  var runtimeFilePath = require.resolve("react-refresh/cjs/react-refresh-runtime.development.js");
184
184
  var runtimeCode = `
@@ -265,9 +265,7 @@ function isComponentLikeName(name) {
265
265
  }
266
266
 
267
267
  // src/jsx-runtime/babel-import-to-require.ts
268
- function babelImportToRequire({
269
- types: t
270
- }) {
268
+ function babelImportToRequire({ types: t }) {
271
269
  return {
272
270
  visitor: {
273
271
  ImportDeclaration(path) {
@@ -312,7 +310,7 @@ async function restoreJSX(babel2, code, filename) {
312
310
  parserOpts: {
313
311
  plugins: ["jsx"]
314
312
  },
315
- plugins: [await babelRestoreJSX]
313
+ plugins: [(await babelRestoreJSX).default]
316
314
  });
317
315
  return [result == null ? void 0 : result.ast, isCommonJS];
318
316
  }
@@ -330,7 +328,7 @@ function parseReactAlias(code) {
330
328
 
331
329
  // src/index.ts
332
330
  function viteReact(opts = {}) {
333
- var _a, _b, _c;
331
+ var _a;
334
332
  let base = "/";
335
333
  let filter = (0, import_pluginutils.createFilter)(opts.include, opts.exclude);
336
334
  let isProduction = true;
@@ -338,8 +336,15 @@ function viteReact(opts = {}) {
338
336
  let skipFastRefresh = opts.fastRefresh === false;
339
337
  let skipReactImport = false;
340
338
  const useAutomaticRuntime = opts.jsxRuntime !== "classic";
341
- const userPlugins = ((_a = opts.babel) == null ? void 0 : _a.plugins) || [];
342
- const userParserPlugins = opts.parserPlugins || ((_c = (_b = opts.babel) == null ? void 0 : _b.parserOpts) == null ? void 0 : _c.plugins) || [];
339
+ const babelOptions = __spreadValues({
340
+ babelrc: false,
341
+ configFile: false
342
+ }, opts.babel);
343
+ babelOptions.plugins || (babelOptions.plugins = []);
344
+ babelOptions.presets || (babelOptions.presets = []);
345
+ babelOptions.overrides || (babelOptions.overrides = []);
346
+ babelOptions.parserOpts || (babelOptions.parserOpts = {});
347
+ (_a = babelOptions.parserOpts).plugins || (_a.plugins = opts.parserPlugins || []);
343
348
  const importReactRE = /(^|\n)import\s+(\*\s+as\s+)?React(,|\s+)/;
344
349
  const fileExtensionRE = /\.[^\/\s\?]+$/;
345
350
  const viteBabel = {
@@ -358,10 +363,17 @@ function viteReact(opts = {}) {
358
363
  skipReactImport = true;
359
364
  config.logger.warn("[@vitejs/plugin-react] This plugin imports React for you automatically, so you can stop using `esbuild.jsxInject` for that purpose.");
360
365
  }
361
- config.plugins.forEach((plugin) => (plugin.name === "react-refresh" || plugin !== viteReactJsx && plugin.name === "vite:react-jsx") && config.logger.warn(`[@vitejs/plugin-react] You should stop using "${plugin.name}" since this plugin conflicts with it.`));
366
+ config.plugins.forEach((plugin) => {
367
+ var _a2;
368
+ const hasConflict = plugin.name === "react-refresh" || plugin !== viteReactJsx && plugin.name === "vite:react-jsx";
369
+ if (hasConflict)
370
+ return config.logger.warn(`[@vitejs/plugin-react] You should stop using "${plugin.name}" since this plugin conflicts with it.`);
371
+ if ((_a2 = plugin.api) == null ? void 0 : _a2.reactBabel) {
372
+ plugin.api.reactBabel(babelOptions, config);
373
+ }
374
+ });
362
375
  },
363
376
  async transform(code, id, options) {
364
- var _a2, _b2, _c2, _d;
365
377
  const ssr = typeof options === "boolean" ? options : (options == null ? void 0 : options.ssr) === true;
366
378
  const [filepath, querystring = ""] = id.split("?");
367
379
  const [extension = ""] = querystring.match(fileExtensionRE) || filepath.match(fileExtensionRE) || [];
@@ -369,10 +381,10 @@ function viteReact(opts = {}) {
369
381
  const isJSX = extension.endsWith("x");
370
382
  const isNodeModules = id.includes("/node_modules/");
371
383
  const isProjectFile = !isNodeModules && (id[0] === "\0" || id.startsWith(projectRoot + "/"));
372
- const plugins = isProjectFile ? [...userPlugins] : [];
384
+ const plugins = isProjectFile ? [...babelOptions.plugins] : [];
373
385
  let useFastRefresh = false;
374
386
  if (!skipFastRefresh && !ssr && !isNodeModules) {
375
- const isReactModule = isJSX || code.includes("react");
387
+ const isReactModule = isJSX || importReactRE.test(code);
376
388
  if (isReactModule && filter(id)) {
377
389
  useFastRefresh = true;
378
390
  plugins.push([
@@ -390,7 +402,8 @@ function viteReact(opts = {}) {
390
402
  await loadPlugin("@babel/plugin-transform-react-jsx" + (isProduction ? "" : "-development")),
391
403
  {
392
404
  runtime: "automatic",
393
- importSource: opts.jsxImportSource
405
+ importSource: opts.jsxImportSource,
406
+ pure: opts.jsxPure !== false
394
407
  }
395
408
  ]);
396
409
  if (isCommonJS) {
@@ -406,12 +419,12 @@ function viteReact(opts = {}) {
406
419
  }
407
420
  }
408
421
  }
409
- const shouldSkip = !plugins.length && !((_a2 = opts.babel) == null ? void 0 : _a2.configFile) && !(isProjectFile && ((_b2 = opts.babel) == null ? void 0 : _b2.babelrc));
422
+ const shouldSkip = !plugins.length && !babelOptions.configFile && !(isProjectFile && babelOptions.babelrc);
410
423
  if (shouldSkip) {
411
424
  return;
412
425
  }
413
426
  const parserPlugins = [
414
- ...userParserPlugins,
427
+ ...babelOptions.parserOpts.plugins,
415
428
  "importMeta",
416
429
  "topLevelAwait",
417
430
  "classProperties",
@@ -424,28 +437,25 @@ function viteReact(opts = {}) {
424
437
  if (/\.tsx?$/.test(extension)) {
425
438
  parserPlugins.push("typescript");
426
439
  }
440
+ const transformAsync2 = ast ? babel.transformFromAstAsync.bind(babel, ast, code) : babel.transformAsync.bind(babel, code);
427
441
  const isReasonReact = extension.endsWith(".bs.js");
428
- const babelOpts = __spreadProps(__spreadValues({
429
- babelrc: false,
430
- configFile: false
431
- }, opts.babel), {
442
+ const result = await transformAsync2(__spreadProps(__spreadValues({}, babelOptions), {
432
443
  ast: !isReasonReact,
433
444
  root: projectRoot,
434
445
  filename: id,
435
446
  sourceFileName: filepath,
436
- parserOpts: __spreadProps(__spreadValues({}, (_c2 = opts.babel) == null ? void 0 : _c2.parserOpts), {
447
+ parserOpts: __spreadProps(__spreadValues({}, babelOptions.parserOpts), {
437
448
  sourceType: "module",
438
449
  allowAwaitOutsideFunction: true,
439
450
  plugins: parserPlugins
440
451
  }),
441
- generatorOpts: __spreadProps(__spreadValues({}, (_d = opts.babel) == null ? void 0 : _d.generatorOpts), {
452
+ generatorOpts: __spreadProps(__spreadValues({}, babelOptions.generatorOpts), {
442
453
  decoratorsBeforeExport: true
443
454
  }),
444
455
  plugins,
445
456
  sourceMaps: true,
446
457
  inputSourceMap: false
447
- });
448
- const result = ast ? await babel.transformFromAstAsync(ast, code, babelOpts) : await babel.transformAsync(code, babelOpts);
458
+ }));
449
459
  if (result) {
450
460
  let code2 = result.code;
451
461
  if (useFastRefresh && /\$RefreshReg\$\(/.test(code2)) {
@@ -520,10 +530,8 @@ function viteReact(opts = {}) {
520
530
  }
521
531
  viteReact.preambleCode = preambleCode;
522
532
  function loadPlugin(path) {
523
- return Promise.resolve().then(() => __toModule(require(path))).then((module2) => module2.default || module2);
533
+ return Promise.resolve().then(() => __toESM(require(path))).then((module2) => module2.default || module2);
524
534
  }
525
- module.exports = viteReact;
526
- viteReact["default"] = viteReact;
527
535
  // Annotate the CommonJS export names for ESM import in node:
528
536
  0 && (module.exports = {});
529
537
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-react",
3
- "version": "1.1.3",
3
+ "version": "1.3.0",
4
4
  "license": "MIT",
5
5
  "author": "Evan You",
6
6
  "contributors": [
@@ -15,10 +15,10 @@
15
15
  "scripts": {
16
16
  "dev": "tsc -p . -w --incremental",
17
17
  "build": "rimraf dist && run-s build-bundle build-types",
18
- "build-bundle": "esbuild src/index.ts --bundle --platform=node --target=node12 --external:@babel/* --external:@rollup/* --external:resolve --external:react-refresh/* --outfile=dist/index.js",
18
+ "build-bundle": "esbuild src/index.ts --bundle --platform=node --target=node12 --external:@babel/* --external:@rollup/* --external:resolve --external:react-refresh/* --outfile=dist/index.js && npm run patch-dist",
19
+ "patch-dist": "ts-node ../../scripts/patchEsbuildDist.ts dist/index.js viteReact",
19
20
  "build-types": "tsc -p . --emitDeclarationOnly --outDir temp && api-extractor run && rimraf temp",
20
- "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . --lerna-package plugin-react",
21
- "release": "node ../../scripts/release.cjs"
21
+ "prepublishOnly": "(cd ../vite && npm run build) && npm run build"
22
22
  },
23
23
  "engines": {
24
24
  "node": ">=12.0.0"
@@ -33,13 +33,13 @@
33
33
  },
34
34
  "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-react#readme",
35
35
  "dependencies": {
36
- "@babel/core": "^7.16.0",
37
- "@babel/plugin-transform-react-jsx": "^7.16.0",
38
- "@babel/plugin-transform-react-jsx-development": "^7.16.0",
39
- "@babel/plugin-transform-react-jsx-self": "^7.16.0",
40
- "@babel/plugin-transform-react-jsx-source": "^7.16.0",
41
- "@rollup/pluginutils": "^4.1.1",
36
+ "@babel/core": "^7.17.8",
37
+ "@babel/plugin-transform-react-jsx": "^7.17.3",
38
+ "@babel/plugin-transform-react-jsx-development": "^7.16.7",
39
+ "@babel/plugin-transform-react-jsx-self": "^7.16.7",
40
+ "@babel/plugin-transform-react-jsx-source": "^7.16.7",
41
+ "@rollup/pluginutils": "^4.2.0",
42
42
  "react-refresh": "^0.11.0",
43
- "resolve": "^1.20.0"
43
+ "resolve": "^1.22.0"
44
44
  }
45
45
  }
package/src/index.ts CHANGED
@@ -32,17 +32,57 @@ export interface Options {
32
32
  * @default "react"
33
33
  */
34
34
  jsxImportSource?: string
35
+ /**
36
+ * Set this to `true` to annotate the JSX factory with `\/* @__PURE__ *\/`.
37
+ * This option is ignored when `jsxRuntime` is not `"automatic"`.
38
+ * @default true
39
+ */
40
+ jsxPure?: boolean
35
41
 
36
42
  /**
37
43
  * Babel configuration applied in both dev and prod.
38
44
  */
39
- babel?: TransformOptions
45
+ babel?: BabelOptions
40
46
  /**
41
47
  * @deprecated Use `babel.parserOpts.plugins` instead
42
48
  */
43
49
  parserPlugins?: ParserOptions['plugins']
44
50
  }
45
51
 
52
+ export type BabelOptions = Omit<
53
+ TransformOptions,
54
+ | 'ast'
55
+ | 'filename'
56
+ | 'root'
57
+ | 'sourceFileName'
58
+ | 'sourceMaps'
59
+ | 'inputSourceMap'
60
+ >
61
+
62
+ /**
63
+ * The object type used by the `options` passed to plugins with
64
+ * an `api.reactBabel` method.
65
+ */
66
+ export interface ReactBabelOptions extends BabelOptions {
67
+ plugins: Extract<BabelOptions['plugins'], any[]>
68
+ presets: Extract<BabelOptions['presets'], any[]>
69
+ overrides: Extract<BabelOptions['overrides'], any[]>
70
+ parserOpts: ParserOptions & {
71
+ plugins: Extract<ParserOptions['plugins'], any[]>
72
+ }
73
+ }
74
+
75
+ declare module 'vite' {
76
+ export interface Plugin {
77
+ api?: {
78
+ /**
79
+ * Manipulate the Babel options of `@vitejs/plugin-react`
80
+ */
81
+ reactBabel?: (options: ReactBabelOptions, config: ResolvedConfig) => void
82
+ }
83
+ }
84
+ }
85
+
46
86
  export default function viteReact(opts: Options = {}): PluginOption[] {
47
87
  // Provide default values for Rollup compat.
48
88
  let base = '/'
@@ -54,11 +94,19 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
54
94
 
55
95
  const useAutomaticRuntime = opts.jsxRuntime !== 'classic'
56
96
 
57
- const userPlugins = opts.babel?.plugins || []
58
- const userParserPlugins =
59
- opts.parserPlugins || opts.babel?.parserOpts?.plugins || []
97
+ const babelOptions = {
98
+ babelrc: false,
99
+ configFile: false,
100
+ ...opts.babel
101
+ } as ReactBabelOptions
60
102
 
61
- // Support pattens like:
103
+ babelOptions.plugins ||= []
104
+ babelOptions.presets ||= []
105
+ babelOptions.overrides ||= []
106
+ babelOptions.parserOpts ||= {} as any
107
+ babelOptions.parserOpts.plugins ||= opts.parserPlugins || []
108
+
109
+ // Support patterns like:
62
110
  // - import * as React from 'react';
63
111
  // - import React from 'react';
64
112
  // - import React, {useEffect} from 'react';
@@ -88,15 +136,21 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
88
136
  )
89
137
  }
90
138
 
91
- config.plugins.forEach(
92
- (plugin) =>
93
- (plugin.name === 'react-refresh' ||
94
- (plugin !== viteReactJsx && plugin.name === 'vite:react-jsx')) &&
95
- config.logger.warn(
139
+ config.plugins.forEach((plugin) => {
140
+ const hasConflict =
141
+ plugin.name === 'react-refresh' ||
142
+ (plugin !== viteReactJsx && plugin.name === 'vite:react-jsx')
143
+
144
+ if (hasConflict)
145
+ return config.logger.warn(
96
146
  `[@vitejs/plugin-react] You should stop using "${plugin.name}" ` +
97
147
  `since this plugin conflicts with it.`
98
148
  )
99
- )
149
+
150
+ if (plugin.api?.reactBabel) {
151
+ plugin.api.reactBabel(babelOptions, config)
152
+ }
153
+ })
100
154
  },
101
155
  async transform(code, id, options) {
102
156
  const ssr = typeof options === 'boolean' ? options : options?.ssr === true
@@ -113,12 +167,12 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
113
167
  const isProjectFile =
114
168
  !isNodeModules && (id[0] === '\0' || id.startsWith(projectRoot + '/'))
115
169
 
116
- const plugins = isProjectFile ? [...userPlugins] : []
170
+ const plugins = isProjectFile ? [...babelOptions.plugins] : []
117
171
 
118
172
  let useFastRefresh = false
119
173
  if (!skipFastRefresh && !ssr && !isNodeModules) {
120
174
  // Modules with .js or .ts extension must import React.
121
- const isReactModule = isJSX || code.includes('react')
175
+ const isReactModule = isJSX || importReactRE.test(code)
122
176
  if (isReactModule && filter(id)) {
123
177
  useFastRefresh = true
124
178
  plugins.push([
@@ -147,7 +201,8 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
147
201
  ),
148
202
  {
149
203
  runtime: 'automatic',
150
- importSource: opts.jsxImportSource
204
+ importSource: opts.jsxImportSource,
205
+ pure: opts.jsxPure !== false
151
206
  }
152
207
  ])
153
208
 
@@ -179,15 +234,15 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
179
234
  // module, including node_modules and linked packages.
180
235
  const shouldSkip =
181
236
  !plugins.length &&
182
- !opts.babel?.configFile &&
183
- !(isProjectFile && opts.babel?.babelrc)
237
+ !babelOptions.configFile &&
238
+ !(isProjectFile && babelOptions.babelrc)
184
239
 
185
240
  if (shouldSkip) {
186
241
  return // Avoid parsing if no plugins exist.
187
242
  }
188
243
 
189
- const parserPlugins: typeof userParserPlugins = [
190
- ...userParserPlugins,
244
+ const parserPlugins: typeof babelOptions.parserOpts.plugins = [
245
+ ...babelOptions.parserOpts.plugins,
191
246
  'importMeta',
192
247
  // This plugin is applied before esbuild transforms the code,
193
248
  // so we need to enable some stage 3 syntax that is supported in
@@ -206,35 +261,32 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
206
261
  parserPlugins.push('typescript')
207
262
  }
208
263
 
209
- const isReasonReact = extension.endsWith('.bs.js')
264
+ const transformAsync = ast
265
+ ? babel.transformFromAstAsync.bind(babel, ast, code)
266
+ : babel.transformAsync.bind(babel, code)
210
267
 
211
- const babelOpts: TransformOptions = {
212
- babelrc: false,
213
- configFile: false,
214
- ...opts.babel,
268
+ const isReasonReact = extension.endsWith('.bs.js')
269
+ const result = await transformAsync({
270
+ ...babelOptions,
215
271
  ast: !isReasonReact,
216
272
  root: projectRoot,
217
273
  filename: id,
218
274
  sourceFileName: filepath,
219
275
  parserOpts: {
220
- ...opts.babel?.parserOpts,
276
+ ...babelOptions.parserOpts,
221
277
  sourceType: 'module',
222
278
  allowAwaitOutsideFunction: true,
223
279
  plugins: parserPlugins
224
280
  },
225
281
  generatorOpts: {
226
- ...opts.babel?.generatorOpts,
282
+ ...babelOptions.generatorOpts,
227
283
  decoratorsBeforeExport: true
228
284
  },
229
285
  plugins,
230
286
  sourceMaps: true,
231
287
  // Vite handles sourcemap flattening
232
288
  inputSourceMap: false as any
233
- }
234
-
235
- const result = ast
236
- ? await babel.transformFromAstAsync(ast, code, babelOpts)
237
- : await babel.transformAsync(code, babelOpts)
289
+ })
238
290
 
239
291
  if (result) {
240
292
  let code = result.code!
@@ -323,5 +375,8 @@ function loadPlugin(path: string): Promise<any> {
323
375
  }
324
376
 
325
377
  // overwrite for cjs require('...')() usage
326
- module.exports = viteReact
327
- viteReact['default'] = viteReact
378
+ // The following lines are inserted by scripts/patchEsbuildDist.ts,
379
+ // this doesn't bundle correctly after esbuild 0.14.4
380
+ //
381
+ // module.exports = viteReact
382
+ // viteReact['default'] = viteReact
@@ -1,3 +1,4 @@
1
+ import type * as babelCore from '@babel/core'
1
2
  import type { types as t, Visitor } from '@babel/core'
2
3
 
3
4
  /**
@@ -9,9 +10,7 @@ import type { types as t, Visitor } from '@babel/core'
9
10
  *
10
11
  * var _jsx = require("react/jsx-runtime").jsx
11
12
  */
12
- export function babelImportToRequire({
13
- types: t
14
- }: typeof import('@babel/core')): {
13
+ export function babelImportToRequire({ types: t }: typeof babelCore): {
15
14
  visitor: Visitor
16
15
  } {
17
16
  return {
@@ -108,4 +108,10 @@ describe('babel-restore-jsx', () => {
108
108
  )
109
109
  ).toMatchInlineSnapshot(`"<h1>{foo ? <p /> : null}</h1>;"`)
110
110
  })
111
+
112
+ it('should handle lowercase component names', () => {
113
+ expect(jsx('React.createElement(aaa)')).toMatchInlineSnapshot(
114
+ `"React.createElement(aaa);"`
115
+ )
116
+ })
111
117
  })
@@ -2,7 +2,7 @@
2
2
  * https://github.com/flying-sheep/babel-plugin-transform-react-createelement-to-jsx
3
3
  * @license GNU General Public License v3.0
4
4
  */
5
- import * as babel from '@babel/core'
5
+ import type * as babel from '@babel/core'
6
6
 
7
7
  /**
8
8
  * Visitor factory for babel, converting React.createElement(...) to <jsx ...>...</jsx>
@@ -76,7 +76,7 @@ export default function ({ types: t }: typeof babel): babel.PluginObj {
76
76
  return null
77
77
  }
78
78
 
79
- const name = getJSXIdentifier(node)
79
+ const name = getJSXIdentifier(node, true)
80
80
  if (name != null) {
81
81
  return name
82
82
  }
@@ -152,9 +152,9 @@ export default function ({ types: t }: typeof babel): babel.PluginObj {
152
152
  return children
153
153
  }
154
154
 
155
- function getJSXIdentifier(node: any) {
155
+ function getJSXIdentifier(node: any, tag = false) {
156
156
  //TODO: JSXNamespacedName
157
- if (t.isIdentifier(node)) {
157
+ if (t.isIdentifier(node) && (!tag || node.name.match(/^[A-Z]/))) {
158
158
  return t.jsxIdentifier(node.name)
159
159
  }
160
160
  if (t.isStringLiteral(node)) {
@@ -1,3 +1,4 @@
1
+ import type * as babelCore from '@babel/core'
1
2
  import type { PluginItem, types as t } from '@babel/core'
2
3
 
3
4
  type RestoredJSX = [result: t.File | null | undefined, isCommonJS: boolean]
@@ -8,7 +9,7 @@ const jsxNotFound: RestoredJSX = [null, false]
8
9
 
9
10
  /** Restore JSX from `React.createElement` calls */
10
11
  export async function restoreJSX(
11
- babel: typeof import('@babel/core'),
12
+ babel: typeof babelCore,
12
13
  code: string,
13
14
  filename: string
14
15
  ): Promise<RestoredJSX> {
@@ -56,7 +57,8 @@ export async function restoreJSX(
56
57
  parserOpts: {
57
58
  plugins: ['jsx']
58
59
  },
59
- plugins: [await babelRestoreJSX]
60
+ // @ts-ignore
61
+ plugins: [(await babelRestoreJSX).default]
60
62
  })
61
63
 
62
64
  return [result?.ast, isCommonJS]
package/CHANGELOG.md DELETED
@@ -1,117 +0,0 @@
1
- ## [1.1.3](https://github.com/vitejs/vite/compare/plugin-react@1.1.2...plugin-react@1.1.3) (2021-12-13)
2
-
3
-
4
- ### Bug Fixes
5
-
6
- * **plugin-react:** only detect preamble in hmr context ([#6096](https://github.com/vitejs/vite/issues/6096)) ([8735294](https://github.com/vitejs/vite/commit/8735294055ce16308a6b8302eba4538f4a2931d0))
7
-
8
-
9
-
10
- ## [1.1.2](https://github.com/vitejs/vite/compare/plugin-react@1.1.1...plugin-react@1.1.2) (2021-12-13)
11
-
12
-
13
- ### Bug Fixes
14
-
15
- * ignore babel config when running restore-jsx ([#6047](https://github.com/vitejs/vite/issues/6047)) ([9c2843c](https://github.com/vitejs/vite/commit/9c2843cf0506844ee32f042a04c22c440434df2a))
16
-
17
-
18
-
19
- ## [1.1.1](https://github.com/vitejs/vite/compare/plugin-react@1.1.0...plugin-react@1.1.1) (2021-12-07)
20
-
21
-
22
-
23
- # [1.1.0](https://github.com/vitejs/vite/compare/plugin-react@1.1.0-beta.1...plugin-react@1.1.0) (2021-11-22)
24
-
25
-
26
-
27
- # [1.1.0-beta.1](https://github.com/vitejs/vite/compare/plugin-react@1.1.0-beta.0...plugin-react@1.1.0-beta.1) (2021-11-19)
28
-
29
-
30
- ### Bug Fixes
31
-
32
- * **plugin-react:** apply `babel.plugins` to project files only ([#5255](https://github.com/vitejs/vite/issues/5255)) ([377d0be](https://github.com/vitejs/vite/commit/377d0be5cf85a50240e160beaaafda77b7199452))
33
- * **plugin-react:** remove querystring from sourcemap filename ([#5760](https://github.com/vitejs/vite/issues/5760)) ([d93a9fa](https://github.com/vitejs/vite/commit/d93a9fab8986f3659e79d7b0b065e99ef625a5dd))
34
- * **plugin-react:** restore usage of extension instead of id ([#5761](https://github.com/vitejs/vite/issues/5761)) ([59471b1](https://github.com/vitejs/vite/commit/59471b186612d3da0083543e23d660747d3287f3))
35
- * **plugin-react:** uncompiled JSX in linked pkgs ([#5669](https://github.com/vitejs/vite/issues/5669)) ([41a7c9c](https://github.com/vitejs/vite/commit/41a7c9ccfbc1a7bc60aec672056eac3966ddd036))
36
-
37
-
38
-
39
- # [1.1.0-beta.0](https://github.com/vitejs/vite/compare/plugin-react@1.0.6...plugin-react@1.1.0-beta.0) (2021-10-28)
40
-
41
-
42
- ### Bug Fixes
43
-
44
- * **plugin-react:** avoid mangling the sourcemaps of virtual modules ([#5421](https://github.com/vitejs/vite/issues/5421)) ([8556ffe](https://github.com/vitejs/vite/commit/8556ffe3c59952d7e64565422bf433699e97756e))
45
-
46
-
47
-
48
- ## [1.0.6](https://github.com/vitejs/vite/compare/plugin-react@1.0.5...plugin-react@1.0.6) (2021-10-25)
49
-
50
-
51
- ### Bug Fixes
52
-
53
- * **plugin-react:** account for querystring in transform hook ([#5333](https://github.com/vitejs/vite/issues/5333)) ([13c3813](https://github.com/vitejs/vite/commit/13c381368caf8302a0c5b7cec07dfc0eb344bede))
54
-
55
-
56
-
57
- ## [1.0.5](https://github.com/vitejs/vite/compare/plugin-react@1.0.4...plugin-react@1.0.5) (2021-10-18)
58
-
59
-
60
- ### Bug Fixes
61
-
62
- * **plugin-react:** fix regex for react imports ([#5274](https://github.com/vitejs/vite/issues/5274)) ([00b3e4f](https://github.com/vitejs/vite/commit/00b3e4fe102652b2d92e76a05e8c7a5b766b1d03))
63
- * **plugin-react:** transform .mjs files ([#5314](https://github.com/vitejs/vite/issues/5314)) ([8ce2ea1](https://github.com/vitejs/vite/commit/8ce2ea17d51b80c660f2cdca7844d4fc6991baed))
64
-
65
-
66
-
67
- ## [1.0.4](https://github.com/vitejs/vite/compare/plugin-react@1.0.3...plugin-react@1.0.4) (2021-10-11)
68
-
69
-
70
-
71
- ## [1.0.3](https://github.com/vitejs/vite/compare/plugin-react@1.0.2...plugin-react@1.0.3) (2021-10-11)
72
-
73
-
74
- ### Bug Fixes
75
-
76
- * **plugin-react:** turn off jsx for .ts ([#5198](https://github.com/vitejs/vite/issues/5198)) ([916f9d3](https://github.com/vitejs/vite/commit/916f9d3984d5e83f7cb869b3606a1f043a814b97)), closes [#5102](https://github.com/vitejs/vite/issues/5102)
77
-
78
-
79
-
80
- ## [1.0.2](https://github.com/vitejs/vite/compare/plugin-react@1.0.1...plugin-react@1.0.2) (2021-10-05)
81
-
82
-
83
- ### Bug Fixes
84
-
85
- * **plugin-react:** respect `opts.fastRefresh` in viteBabel ([#5139](https://github.com/vitejs/vite/issues/5139)) ([5cf4e69](https://github.com/vitejs/vite/commit/5cf4e69cd3afc7f960e02072171c7c441747e8f0))
86
-
87
-
88
-
89
- ## [1.0.1](https://github.com/vitejs/vite/compare/plugin-react@1.0.0...plugin-react@1.0.1) (2021-09-22)
90
-
91
-
92
- ### Bug Fixes
93
-
94
- * **plugin-react:** inconsistent error warning ([#5031](https://github.com/vitejs/vite/issues/5031)) ([89ba8ce](https://github.com/vitejs/vite/commit/89ba8cedb8636968516bc38b37e1d2d5ed6234bb))
95
-
96
-
97
- ### Features
98
-
99
- * **plugin-react:** pre-optimize jsx-dev-runtime ([#5036](https://github.com/vitejs/vite/issues/5036)) ([a34dd27](https://github.com/vitejs/vite/commit/a34dd2725e64fedf626e23ba9ced480f5465a59b))
100
-
101
-
102
-
103
- # [1.0.0](https://github.com/vitejs/vite/compare/plugin-react@1.0.0-beta.0...plugin-react@1.0.0) (2021-09-22)
104
-
105
- See the [readme](https://github.com/aleclarson/vite/blob/f8129ce6e87684eb7a4edd8106351c5d98207d7b/packages/plugin-react/README.md#vitejsplugin-react-) for more information.
106
-
107
- - Support for [automatic JSX runtime](https://github.com/alloc/vite-react-jsx)
108
- - Babel integration for both development and production builds
109
- - Add `react` and `react-dom` to [`resolve.dedupe`](https://vitejs.dev/config/#resolve-dedupe) automatically
110
-
111
- Thanks to @aleclarson and @pengx17 for preparing this release!
112
-
113
- # Legacy
114
-
115
- Before `@vitejs/plugin-react`, there was `@vitejs/plugin-react-refresh`.
116
-
117
- See its changelog [here.](https://github.com/vitejs/vite/blob/b9e837a2aa2c1a7a8f93d4b19df9f72fd3c6fb09/packages/plugin-react-refresh/CHANGELOG.md)