diff --git a/.changeset/fast-hairs-work.md b/.changeset/fast-hairs-work.md new file mode 100644 index 000000000000..017e6ff545d0 --- /dev/null +++ b/.changeset/fast-hairs-work.md @@ -0,0 +1,5 @@ +--- +swc_common: major +--- + +refactor(es/react): Split jsx into automatic/classic diff --git a/Cargo.lock b/Cargo.lock index 0ea98c570a9b..6b4cd766db85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6023,6 +6023,7 @@ dependencies = [ "bytes-str", "dashmap 5.5.3", "indexmap 2.7.1", + "memchr", "once_cell", "rayon", "rustc-hash 2.1.1", diff --git a/bindings/binding_core_wasm/__tests__/simple.js b/bindings/binding_core_wasm/__tests__/simple.js index f521ee1d9f61..3d2dbf31c32a 100644 --- a/bindings/binding_core_wasm/__tests__/simple.js +++ b/bindings/binding_core_wasm/__tests__/simple.js @@ -113,8 +113,8 @@ describe("parse", () => { "ctxt": 2, "optional": false, "span": { - "end": 254, - "start": 251, + "end": 114, + "start": 111, }, "type": "Identifier", "value": "Foo", @@ -122,8 +122,8 @@ describe("parse", () => { "implements": [], "isAbstract": false, "span": { - "end": 257, - "start": 245, + "end": 117, + "start": 105, }, "superClass": null, "superTypeParams": null, @@ -133,8 +133,8 @@ describe("parse", () => { ], "interpreter": null, "span": { - "end": 257, - "start": 245, + "end": 117, + "start": 105, }, "type": "Module", } @@ -159,8 +159,8 @@ describe("parse", () => { "ctxt": 2, "optional": false, "span": { - "end": 267, - "start": 264, + "end": 127, + "start": 124, }, "type": "Identifier", "value": "Foo", @@ -168,8 +168,8 @@ describe("parse", () => { "implements": [], "isAbstract": false, "span": { - "end": 270, - "start": 258, + "end": 130, + "start": 118, }, "superClass": null, "superTypeParams": null, @@ -179,8 +179,8 @@ describe("parse", () => { ], "interpreter": null, "span": { - "end": 270, - "start": 258, + "end": 130, + "start": 118, }, "type": "Module", } diff --git a/bindings/binding_core_wasm/src/types.rs b/bindings/binding_core_wasm/src/types.rs index 1562e264811a..0ceafa570f8a 100644 --- a/bindings/binding_core_wasm/src/types.rs +++ b/bindings/binding_core_wasm/src/types.rs @@ -793,14 +793,16 @@ export interface EsParserConfig { importAssertions?: boolean; } +type JSXPreset = "react" | "react-jsx" | "react-jsxdev" | "preserve" | "react-native"; + /** * Options for transform. */ export interface TransformConfig { /** - * Effective only if `syntax` supports ƒ. + * Effective only if `syntax` supports. */ - react?: ReactConfig; + react?: JSXPreset | ReactConfig; constModules?: ConstModulesConfig; @@ -889,7 +891,7 @@ export interface ReactConfig { /** * jsx runtime */ - runtime?: 'automatic' | 'classic' + runtime?: 'automatic' | 'classic' | 'preserve'; /** * Declares the module specifier to be used for importing the `jsx` and `jsxs` factory functions when using `runtime` 'automatic' diff --git a/crates/jsdoc/tests/fixture.rs b/crates/jsdoc/tests/fixture.rs index db42cec14881..3e74e554f99e 100644 --- a/crates/jsdoc/tests/fixture.rs +++ b/crates/jsdoc/tests/fixture.rs @@ -154,4 +154,17 @@ impl Comments for SwcComments { leading.push(pure_comment); } } + + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + for entry in self.leading.iter() { + for cmt in entry.value() { + f(cmt); + } + } + for entry in self.trailing.iter() { + for cmt in entry.value() { + f(cmt); + } + } + } } diff --git a/crates/swc/benches/oxc.rs b/crates/swc/benches/oxc.rs index 307b03a9e0c1..58f1b86b59c2 100644 --- a/crates/swc/benches/oxc.rs +++ b/crates/swc/benches/oxc.rs @@ -62,8 +62,11 @@ fn full_group(c: &mut Criterion) { })), transform: Some(TransformConfig { react: swc_ecma_transforms::react::Options { - runtime: Some(Runtime::Automatic), - development: Some(react_dev), + runtime: Runtime::Automatic(Default::default()), + common: swc_ecma_transforms::react::CommonConfig { + development: react_dev.into(), + ..Default::default() + }, ..Default::default() }, ..Default::default() diff --git a/crates/swc/src/config/mod.rs b/crates/swc/src/config/mod.rs index 544ade127381..4f1ef87df77b 100644 --- a/crates/swc/src/config/mod.rs +++ b/crates/swc/src/config/mod.rs @@ -57,7 +57,7 @@ use swc_ecma_transforms::{ decorators, explicit_resource_management::explicit_resource_management, export_default_from, import_attributes, }, - react::{self, default_pragma, default_pragma_frag}, + react::{self}, resolver, typescript::{self, TsImportExportAssignConfig}, Assumptions, @@ -295,16 +295,42 @@ impl Options { let mut transform = transform.into_inner().unwrap_or_default(); - // Do a resolver pass before everything. - // - // We do this before creating custom passes, so custom passses can use the - // variable management system based on the syntax contexts. if syntax.typescript() { assumptions.set_class_methods |= !transform.use_define_for_class_fields.into_bool(); } assumptions.set_public_class_fields |= !transform.use_define_for_class_fields.into_bool(); + // Do a resolver pass before everything. + // + // We do this before creating custom passes, so custom passses can use the + // variable management system based on the syntax contexts. + // + // Exception: Classic JSX transformation runs before the resolver + // because it's a context-free syntactic transformation that doesn't require + // scope information. + // Running resolver first would mark identifiers (like JSX pragma functions) + // with syntax contexts, making it harder for the JSX transform to + // handle pragma references that should resolve to local scope declarations. + + let jsx_pass = 'jsx_pass: { + if !syntax.jsx() { + break 'jsx_pass None; + } + + let (mut before_resolver, after_resolver) = react::react( + cm.clone(), + comments.cloned(), + transform.react, + top_level_mark, + unresolved_mark, + ); + + program.mutate(&mut before_resolver); + + Some(after_resolver) + }; + program.visit_mut_with(&mut resolver( unresolved_mark, top_level_mark, @@ -782,37 +808,9 @@ impl Options { ..Default::default() }; - ( - Optional::new( - typescript::typescript(ts_config, unresolved_mark, top_level_mark), - syntax.typescript() && !syntax.jsx(), - ), - Optional::new( - typescript::tsx::>( - cm.clone(), - ts_config, - typescript::TsxConfig { - pragma: Some( - transform - .react - .pragma - .clone() - .unwrap_or_else(default_pragma), - ), - pragma_frag: Some( - transform - .react - .pragma_frag - .clone() - .unwrap_or_else(default_pragma_frag), - ), - }, - comments.map(|v| v as _), - unresolved_mark, - top_level_mark, - ), - syntax.typescript() && syntax.jsx(), - ), + Optional::new( + typescript::typescript(ts_config, unresolved_mark, top_level_mark), + syntax.typescript(), ) }, ), @@ -820,16 +818,7 @@ impl Options { plugin_transforms.take(), custom_before_pass(&program), // handle jsx - Optional::new( - react::react::<&dyn Comments>( - cm.clone(), - comments.map(|v| v as _), - transform.react, - top_level_mark, - unresolved_mark, - ), - syntax.jsx(), - ), + jsx_pass, built_pass, Optional::new(jest::jest(), transform.hidden.jest.into_bool()), Optional::new( diff --git a/crates/swc/tests/fixture/codegen/jsx-1/output/index.js b/crates/swc/tests/fixture/codegen/jsx-1/output/index.js index 6d260ba40c48..54bcd2565569 100644 --- a/crates/swc/tests/fixture/codegen/jsx-1/output/index.js +++ b/crates/swc/tests/fixture/codegen/jsx-1/output/index.js @@ -1,4 +1,5 @@ -export default /*#__PURE__*/ React.createElement(A, { +import { jsx as _jsx } from "react/jsx-runtime"; +export default /*#__PURE__*/ _jsx(A, { className: b, header: "C", subheader: "D E" diff --git a/crates/swc/tests/fixture/issues-10xxx/10018/output/idnex.jsx b/crates/swc/tests/fixture/issues-10xxx/10018/output/idnex.jsx index 130d3db9d6be..fa07044ef27c 100644 --- a/crates/swc/tests/fixture/issues-10xxx/10018/output/idnex.jsx +++ b/crates/swc/tests/fixture/issues-10xxx/10018/output/idnex.jsx @@ -1,3 +1,3 @@ -var _require = require("foo/jsx-runtime"), _jsx = _require.jsx; +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; ; _jsx("a", {}); diff --git a/crates/swc/tests/fixture/issues-10xxx/10553/input/.swcrc b/crates/swc/tests/fixture/issues-10xxx/10553/input/.swcrc new file mode 100644 index 000000000000..c22a48b431d7 --- /dev/null +++ b/crates/swc/tests/fixture/issues-10xxx/10553/input/.swcrc @@ -0,0 +1,25 @@ +{ + "jsc": { + "parser": { + "syntax": "ecmascript", + "exportDefaultFrom": true, + "jsx": true + }, + "target": "es5", + "loose": false, + "minify": { + "compress": false, + "mangle": false + }, + "transform": { + "react": { + "runtime": "classic" + } + } + }, + "module": { + "type": "es6" + }, + "minify": false, + "isModule": true +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-10xxx/10553/input/input.jsx b/crates/swc/tests/fixture/issues-10xxx/10553/input/input.jsx new file mode 100644 index 000000000000..0a7f4abb3515 --- /dev/null +++ b/crates/swc/tests/fixture/issues-10xxx/10553/input/input.jsx @@ -0,0 +1,3 @@ +export function Home(React) { + return
Hello World {count}
+} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-10xxx/10553/output/input.jsx b/crates/swc/tests/fixture/issues-10xxx/10553/output/input.jsx new file mode 100644 index 000000000000..6acc5e7544dd --- /dev/null +++ b/crates/swc/tests/fixture/issues-10xxx/10553/output/input.jsx @@ -0,0 +1,3 @@ +export function Home(React) { + return React.createElement("div", null, "Hello World ", count); +} diff --git a/crates/swc/tests/fixture/issues-10xxx/10651/output/input.jsx b/crates/swc/tests/fixture/issues-10xxx/10651/output/input.jsx index b7509f764957..7dba696fe6fd 100644 --- a/crates/swc/tests/fixture/issues-10xxx/10651/output/input.jsx +++ b/crates/swc/tests/fixture/issues-10xxx/10651/output/input.jsx @@ -1,3 +1,6 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; var a = function() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, "\xb7"); + return /*#__PURE__*/ _jsx(_Fragment, { + children: "\xb7" + }); }; diff --git a/crates/swc/tests/fixture/issues-1xxx/1233/case-1/output/index.js b/crates/swc/tests/fixture/issues-1xxx/1233/case-1/output/index.js index aecbb52f1641..cbeea3eda25f 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1233/case-1/output/index.js +++ b/crates/swc/tests/fixture/issues-1xxx/1233/case-1/output/index.js @@ -1,5 +1,6 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; function Component() { - return /*#__PURE__*/ React.createElement("div", { + return /*#__PURE__*/ _jsx("div", { name: "A B" }); } diff --git a/crates/swc/tests/fixture/issues-1xxx/1446/case1/output/input.tsx b/crates/swc/tests/fixture/issues-1xxx/1446/case1/output/input.tsx index fc3e567e8c96..a0ee7ec5ed4a 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1446/case1/output/input.tsx +++ b/crates/swc/tests/fixture/issues-1xxx/1446/case1/output/input.tsx @@ -1 +1,4 @@ -const Span = /*#__PURE__*/ React.createElement("span", null, "with "); +const { jsx: _jsx } = require("react/jsx-runtime"); +const Span = /*#__PURE__*/ _jsx("span", { + children: "with " +}); diff --git a/crates/swc/tests/fixture/issues-1xxx/1446/case2/output/input.tsx b/crates/swc/tests/fixture/issues-1xxx/1446/case2/output/input.tsx index a3f74e24fc53..b396cd9f11f4 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1446/case2/output/input.tsx +++ b/crates/swc/tests/fixture/issues-1xxx/1446/case2/output/input.tsx @@ -1 +1,4 @@ -const Span = /*#__PURE__*/ React.createElement("span", null, "with "); +const { jsx: _jsx } = require("react/jsx-runtime"); +const Span = /*#__PURE__*/ _jsx("span", { + children: "with " +}); diff --git a/crates/swc/tests/fixture/issues-1xxx/1446/case3/output/index.tsx b/crates/swc/tests/fixture/issues-1xxx/1446/case3/output/index.tsx index 3e39a02853d6..11f90a78b0bb 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1446/case3/output/index.tsx +++ b/crates/swc/tests/fixture/issues-1xxx/1446/case3/output/index.tsx @@ -1 +1,9 @@ -/*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("span", null, "Hello something long to not trigger line break"), " "); +/*#__PURE__*/ const { jsx: _jsx, jsxs: _jsxs, Fragment: _Fragment } = require("react/jsx-runtime"); +_jsxs(_Fragment, { + children: [ + /*#__PURE__*/ _jsx("span", { + children: "Hello something long to not trigger line break" + }), + " " + ] +}); diff --git a/crates/swc/tests/fixture/issues-1xxx/1479/case-es2020/output/index.tsx b/crates/swc/tests/fixture/issues-1xxx/1479/case-es2020/output/index.tsx index 3b696ffd393c..0ddb5d488178 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1479/case-es2020/output/index.tsx +++ b/crates/swc/tests/fixture/issues-1xxx/1479/case-es2020/output/index.tsx @@ -1,3 +1,4 @@ -const a = /*#__PURE__*/ React.createElement("div", { +const { jsx: _jsx } = require("react/jsx-runtime"); +const a = /*#__PURE__*/ _jsx("div", { id: "abc>" }); diff --git a/crates/swc/tests/fixture/issues-1xxx/1479/case-es5/output/index.tsx b/crates/swc/tests/fixture/issues-1xxx/1479/case-es5/output/index.tsx index 94537d9320aa..8b419ea003ee 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1479/case-es5/output/index.tsx +++ b/crates/swc/tests/fixture/issues-1xxx/1479/case-es5/output/index.tsx @@ -1,3 +1,4 @@ -var a = /*#__PURE__*/ React.createElement("div", { +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; +var a = /*#__PURE__*/ _jsx("div", { id: "abc>" }); diff --git a/crates/swc/tests/fixture/issues-1xxx/1525/case1/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1525/case1/input/.swcrc index bb6114eb9ecf..3958c22e2c67 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1525/case1/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1525/case1/input/.swcrc @@ -8,6 +8,9 @@ "parser": { "syntax": "typescript", "tsx": true + }, + "transform": { + "react": "react" } }, "module": { diff --git a/crates/swc/tests/fixture/issues-1xxx/1661/case1/output/index.js b/crates/swc/tests/fixture/issues-1xxx/1661/case1/output/index.js index 7205b0b7a865..548d9b4c90da 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1661/case1/output/index.js +++ b/crates/swc/tests/fixture/issues-1xxx/1661/case1/output/index.js @@ -1,3 +1,5 @@ -console.log(/*#__PURE__*/ React.createElement("h1", { - value: "abc\\nas" -}, "s")); +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; +console.log(/*#__PURE__*/ _jsx("h1", { + value: "abc\\nas", + children: "s" +})); diff --git a/crates/swc/tests/fixture/issues-1xxx/1687/.input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1687/.input/.swcrc index 68c6aeace690..497dc184c4b8 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1687/.input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1687/.input/.swcrc @@ -7,9 +7,7 @@ "dynamicImport": true }, "transform": { - "react": { - "runtime": "automatic" - } + "react": "react-jsx" }, "externalHelpers": true }, @@ -17,4 +15,4 @@ "coreJs": "3", "mode": "usage" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-1xxx/1726/case1/output/index.tsx b/crates/swc/tests/fixture/issues-1xxx/1726/case1/output/index.tsx index ae4bb930dbf8..2bf005479e4d 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1726/case1/output/index.tsx +++ b/crates/swc/tests/fixture/issues-1xxx/1726/case1/output/index.tsx @@ -1 +1,4 @@ -var foo = /* 1 */ /*#__PURE__*/ React.createElement("h1", null, bar /* 3 */ ); /* 4 */ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; +var foo = /* 1 */ /*#__PURE__*/ _jsx("h1", { + children: bar /* 3 */ +}); /* 4 */ diff --git a/crates/swc/tests/fixture/issues-1xxx/1782/case1/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1782/case1/input/.swcrc index 3c93ebbea517..45cf23157356 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1782/case1/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1782/case1/input/.swcrc @@ -3,6 +3,11 @@ "parser": { "syntax": "typescript", "tsx": true + }, + "transform": { + "react": { + "runtime": "classic" + } } } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-1xxx/1799/case1/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1799/case1/input/.swcrc index f14b75d37da4..5637c6328272 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1799/case1/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1799/case1/input/.swcrc @@ -3,6 +3,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } }, "parser": { @@ -26,4 +29,4 @@ "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-1xxx/1799/case2-no-loose/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1799/case2-no-loose/input/.swcrc index fc94b35d058d..41944efed165 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1799/case2-no-loose/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1799/case2-no-loose/input/.swcrc @@ -3,6 +3,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } }, "parser": { @@ -25,4 +28,4 @@ "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-1xxx/1799/case2/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1799/case2/input/.swcrc index 14d5d977defa..5062edb9a123 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1799/case2/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1799/case2/input/.swcrc @@ -3,6 +3,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } }, "parser": { @@ -26,4 +29,4 @@ "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-1xxx/1799/case3/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1799/case3/input/.swcrc index 75e15f208bfb..3c686297afbd 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1799/case3/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1799/case3/input/.swcrc @@ -3,6 +3,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } }, "parser": { @@ -26,4 +29,4 @@ "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-1xxx/1799/case4/input/.swcrc b/crates/swc/tests/fixture/issues-1xxx/1799/case4/input/.swcrc index 11aa4b18c606..588882d20743 100644 --- a/crates/swc/tests/fixture/issues-1xxx/1799/case4/input/.swcrc +++ b/crates/swc/tests/fixture/issues-1xxx/1799/case4/input/.swcrc @@ -3,6 +3,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } }, "parser": { @@ -26,4 +29,4 @@ "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-2xxx/2037/case1/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2037/case1/output/index.js index 2981991490b9..74404840c5f9 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2037/case1/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2037/case1/output/index.js @@ -1,6 +1,7 @@ +var _to_consumable_array = require("@swc/helpers/_/_to_consumable_array"); +var _require = require("react/jsx-runtime"), _jsxs = _require.jsxs; var A = function() { - return /*#__PURE__*/ React.createElement.apply(React, [ - "div", - null - ]); + return /*#__PURE__*/ _jsxs("div", { + children: _to_consumable_array._([]) + }); }; diff --git a/crates/swc/tests/fixture/issues-2xxx/2139/output/index.tsx b/crates/swc/tests/fixture/issues-2xxx/2139/output/index.tsx index a3bfd54b7cd0..8ce15f1316e2 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2139/output/index.tsx +++ b/crates/swc/tests/fixture/issues-2xxx/2139/output/index.tsx @@ -1,4 +1,5 @@ import { _ as _define_property } from "@swc/helpers/_/_define_property"; +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; class ReusablePayments extends PureComponent { componentDidMount() { this.setDefaultReusablePayment(); @@ -31,7 +32,7 @@ class ReusablePayments extends PureComponent { if (!stripePaymentSources.length) { return null; } - return /*#__PURE__*/ React.createElement(DeletePaymentSourceComponent, { + return /*#__PURE__*/ _jsx(DeletePaymentSourceComponent, { onCompleted: (param)=>{ var deletePaymentSource = param.deletePaymentSource; if (deletePaymentSource.success) { @@ -45,40 +46,64 @@ class ReusablePayments extends PureComponent { }, refetchQueries: [ "ReusablePaymentSources" - ] - }, (deletePaymentSource)=>/*#__PURE__*/ React.createElement("div", { - className: styles.selectionList - }, stripePaymentSources.map((payment)=>{ - var cardIcon = "brand" in payment.paymentEntity ? payment.paymentEntity.brand === "Visa" ? /*#__PURE__*/ React.createElement(Visa, null) : payment.paymentEntity.brand === "MasterCard" ? /*#__PURE__*/ React.createElement(MasterCard, null) : payment.paymentEntity.brand === "American Express" ? /*#__PURE__*/ React.createElement(AmericanExpress, null) : payment.paymentEntity.brand === "Discover" ? /*#__PURE__*/ React.createElement(Discover, null) : null : null; - return /*#__PURE__*/ React.createElement("div", { - key: payment.id, - className: classNames(styles.creditCard, { - [styles.creditCardChecked]: selectedReusablePayment === payment + ], + children: (deletePaymentSource)=>/*#__PURE__*/ _jsx("div", { + className: styles.selectionList, + children: stripePaymentSources.map((payment)=>{ + var cardIcon = "brand" in payment.paymentEntity ? payment.paymentEntity.brand === "Visa" ? /*#__PURE__*/ _jsx(Visa, {}) : payment.paymentEntity.brand === "MasterCard" ? /*#__PURE__*/ _jsx(MasterCard, {}) : payment.paymentEntity.brand === "American Express" ? /*#__PURE__*/ _jsx(AmericanExpress, {}) : payment.paymentEntity.brand === "Discover" ? /*#__PURE__*/ _jsx(Discover, {}) : null : null; + return /*#__PURE__*/ _jsx("div", { + className: classNames(styles.creditCard, { + [styles.creditCardChecked]: selectedReusablePayment === payment + }), + children: /*#__PURE__*/ _jsxs("div", { + className: styles.creditCardContainer, + children: [ + /*#__PURE__*/ _jsx(Radio, { + value: payment.id, + checked: selectedReusablePayment === payment, + onChange: this.handleSelectPayment.bind(this, payment), + children: /*#__PURE__*/ _jsxs("div", { + className: styles.paymentHeader, + children: [ + /*#__PURE__*/ _jsxs("div", { + className: styles.paymentHeaderContainer, + children: [ + cardIcon, + payment.paymentEntity.__typename === "PaymentCard" && /*#__PURE__*/ _jsx("div", { + className: styles.textBold, + children: payment.paymentEntity.brand + }) + ] + }), + /*#__PURE__*/ _jsxs("div", { + className: styles.textSmall, + children: [ + payment.owner && (payment.owner.verifiedName || payment.owner.name), + " ", + "-", + payment.paymentEntity.__typename === "PaymentCard" && ` xxx ${payment.paymentEntity.last4}` + ] + }) + ] + }) + }), + /*#__PURE__*/ _jsx("div", { + className: styles.creditCardActions, + children: /*#__PURE__*/ _jsx(Button, { + onClick: this.handleDeletePaymentSource.bind(this, payment.id, deletePaymentSource), + className: styles.removeCardButton, + variant: "secondary-link", + type: "button", + size: "xsmall", + children: "Remove" + }) + }) + ] + }) + }, payment.id); }) - }, /*#__PURE__*/ React.createElement("div", { - className: styles.creditCardContainer - }, /*#__PURE__*/ React.createElement(Radio, { - value: payment.id, - checked: selectedReusablePayment === payment, - onChange: this.handleSelectPayment.bind(this, payment) - }, /*#__PURE__*/ React.createElement("div", { - className: styles.paymentHeader - }, /*#__PURE__*/ React.createElement("div", { - className: styles.paymentHeaderContainer - }, cardIcon, payment.paymentEntity.__typename === "PaymentCard" && /*#__PURE__*/ React.createElement("div", { - className: styles.textBold - }, payment.paymentEntity.brand)), /*#__PURE__*/ React.createElement("div", { - className: styles.textSmall - }, payment.owner && (payment.owner.verifiedName || payment.owner.name), " ", "-", payment.paymentEntity.__typename === "PaymentCard" && ` xxx ${payment.paymentEntity.last4}`))), /*#__PURE__*/ React.createElement("div", { - className: styles.creditCardActions - }, /*#__PURE__*/ React.createElement(Button, { - onClick: this.handleDeletePaymentSource.bind(this, payment.id, deletePaymentSource), - className: styles.removeCardButton, - variant: "secondary-link", - type: "button", - size: "xsmall" - }, "Remove")))); - }))); + }) + }); } constructor(...args){ super(...args), _define_property(this, "handleSelectPayment", (selected)=>{ diff --git a/crates/swc/tests/fixture/issues-2xxx/2154/case1/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2154/case1/output/index.js index 642ef4f89948..3b801ba321d5 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2154/case1/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2154/case1/output/index.js @@ -1,4 +1,5 @@ -var c = /*#__PURE__*/ React.createElement("img", { +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; +var c = /*#__PURE__*/ _jsx("img", { alt: "caf\xe9" }).props.alt; console.log(c); diff --git a/crates/swc/tests/fixture/issues-2xxx/2162/case1/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2162/case1/output/index.js index 459a5f558380..7df1a2f801ad 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2162/case1/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2162/case1/output/index.js @@ -1,5 +1,8 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; function test() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(A, { - b: "\\" - })); + return /*#__PURE__*/ _jsx(_Fragment, { + children: /*#__PURE__*/ _jsx(A, { + b: "\\" + }) + }); } diff --git a/crates/swc/tests/fixture/issues-2xxx/2162/case2/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2162/case2/output/index.js index 459a5f558380..7df1a2f801ad 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2162/case2/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2162/case2/output/index.js @@ -1,5 +1,8 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; function test() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(A, { - b: "\\" - })); + return /*#__PURE__*/ _jsx(_Fragment, { + children: /*#__PURE__*/ _jsx(A, { + b: "\\" + }) + }); } diff --git a/crates/swc/tests/fixture/issues-2xxx/2162/case3/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2162/case3/output/index.js index 9c477480750b..6f6542338b55 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2162/case3/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2162/case3/output/index.js @@ -1,5 +1,8 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; function test() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(A, { - b: "\\x21" - })); + return /*#__PURE__*/ _jsx(_Fragment, { + children: /*#__PURE__*/ _jsx(A, { + b: "\\x21" + }) + }); } diff --git a/crates/swc/tests/fixture/issues-2xxx/2162/case4/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2162/case4/output/index.js index b49faaa854d3..71fe3d61f3bb 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2162/case4/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2162/case4/output/index.js @@ -1,5 +1,8 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; function test() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(A, { - b: "\\ " - })); + return /*#__PURE__*/ _jsx(_Fragment, { + children: /*#__PURE__*/ _jsx(A, { + b: "\\ " + }) + }); } diff --git a/crates/swc/tests/fixture/issues-2xxx/2162/case5/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2162/case5/output/index.js index 837fffda7c14..b5f39b48bccb 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2162/case5/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2162/case5/output/index.js @@ -1,5 +1,8 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; function test() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(A, { - b: "\\u54e6" - })); + return /*#__PURE__*/ _jsx(_Fragment, { + children: /*#__PURE__*/ _jsx(A, { + b: "\\u54e6" + }) + }); } diff --git a/crates/swc/tests/fixture/issues-2xxx/2162/case6/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2162/case6/output/index.js index b920cb76f91b..762ac9a59d01 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2162/case6/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2162/case6/output/index.js @@ -1,5 +1,8 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; function test() { - return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(A, { - b: "\\'" - })); + return /*#__PURE__*/ _jsx(_Fragment, { + children: /*#__PURE__*/ _jsx(A, { + b: "\\'" + }) + }); } diff --git a/crates/swc/tests/fixture/issues-2xxx/2208/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2208/output/index.js index a60d80223532..81bd8d9196da 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2208/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2208/output/index.js @@ -1,3 +1,6 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; var Component = function() { - return /*#__PURE__*/ React.createElement("pre", null, "| | |"); + return /*#__PURE__*/ _jsx("pre", { + children: "| | |" + }); }; diff --git a/crates/swc/tests/fixture/issues-2xxx/2214/input/.swcrc b/crates/swc/tests/fixture/issues-2xxx/2214/input/.swcrc index 3c93ebbea517..45cf23157356 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2214/input/.swcrc +++ b/crates/swc/tests/fixture/issues-2xxx/2214/input/.swcrc @@ -3,6 +3,11 @@ "parser": { "syntax": "typescript", "tsx": true + }, + "transform": { + "react": { + "runtime": "classic" + } } } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-2xxx/2310/output/index.tsx b/crates/swc/tests/fixture/issues-2xxx/2310/output/index.tsx index 18ff09aca562..7946b79c3a6f 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2310/output/index.tsx +++ b/crates/swc/tests/fixture/issues-2xxx/2310/output/index.tsx @@ -1,6 +1,7 @@ +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; (function(A) { A.Foo = function() { - return /*#__PURE__*/ React.createElement("div", null); + return /*#__PURE__*/ _jsx("div", {}); }; })(A || (A = {})); var A; diff --git a/crates/swc/tests/fixture/issues-2xxx/2351/1/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2351/1/output/index.js index ec58c096bac9..3b1caace4a22 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2351/1/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2351/1/output/index.js @@ -1,3 +1,5 @@ -var a = /*#__PURE__*/ React.createElement("abbr", { - title: "\\d" -}, "\\d"); +var _require = require("react/jsx-runtime"), _jsx = _require.jsx; +var a = /*#__PURE__*/ _jsx("abbr", { + title: "\\d", + children: "\\d" +}); diff --git a/crates/swc/tests/fixture/issues-2xxx/2854/1/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2854/1/output/index.js index fb6df143c295..167630f14731 100644 --- a/crates/swc/tests/fixture/issues-2xxx/2854/1/output/index.js +++ b/crates/swc/tests/fixture/issues-2xxx/2854/1/output/index.js @@ -1,9 +1,10 @@ +import { jsx as _jsx } from "react/jsx-runtime"; export function App() { - return React.createElement(Form, null); + return _jsx(Form, {}); } export function Form(param) { var _param_onChange = param.onChange, onChange = _param_onChange === void 0 ? function() {} : _param_onChange; - return React.createElement("input", { + return _jsx("input", { onChange: function onChange1() { onChange(); } diff --git a/crates/swc/tests/fixture/issues-4xxx/4006/1/output/index.map b/crates/swc/tests/fixture/issues-4xxx/4006/1/output/index.map index b5a7b480da77..abfff23662f6 100644 --- a/crates/swc/tests/fixture/issues-4xxx/4006/1/output/index.map +++ b/crates/swc/tests/fixture/issues-4xxx/4006/1/output/index.map @@ -1,5 +1,5 @@ { - "mappings": ";AAAA,SAASA,IAAI,EAAEC,GAAG,EAAEC,UAAU,QAAQ,MAAM;AAE5C,OAAO,MAAMC,YAAYD;IAkBrBE,SAAS;QACL,OAAOJ,IAAI,CAAC,UAAU,EAAE,IAAI,CAACK,IAAI,CAAC,KAAK,CAAC;IAC5C;IAPA,aAAc;QACV,KAAK,IAbTA,uBAAAA,QAAAA,KAAAA;QAcI,IAAI,CAACA,IAAI,GAAG;IAChB;AAKJ;AAlBI,iBAHSF,KAGFG,UAASL,GAAG,CAAC;;;;IAIpB,CAAC;AAED,iBATSE,KASFI,cAAa;IAChBF,MAAM;QAAEG,MAAMC;IAAO;AACzB;AAWJC,eAAeC,MAAM,CAAC,OAAOR", + "mappings": ";AAAA,SAASA,IAAI,EAAEC,GAAG,EAAEC,UAAU,QAAQ,MAAM;AAE5C,OAAO,MAAMC,YAAYD;IAkBrBE,SAAS;QACL,OAAOJ,IAAI,CAAC,UAAU,EAAE,IAAI,CAACK,IAAI,CAAC,KAAK,CAAC;IAC5C;IAPA,aAAc;QACV,KAAK,IAbTA,uBAAAA,QAAAA;QAcI,IAAI,CAACA,IAAI,GAAG;IAChB;AAKJ;AAlBI,iBAHSF,KAGFG,UAASL,GAAG,CAAC;;;;IAIpB,CAAC;AAED,iBATSE,KASFI,cAAa;IAChBF,MAAM;QAAEG,MAAMC;IAAO;AACzB;AAWJC,eAAeC,MAAM,CAAC,OAAOR", "names": [ "html", "css", diff --git a/crates/swc/tests/fixture/issues-4xxx/4296/1/input/.swcrc b/crates/swc/tests/fixture/issues-4xxx/4296/1/input/.swcrc index e3cbe9493182..2e2a54be93c2 100644 --- a/crates/swc/tests/fixture/issues-4xxx/4296/1/input/.swcrc +++ b/crates/swc/tests/fixture/issues-4xxx/4296/1/input/.swcrc @@ -3,6 +3,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } }, "target": "es2022", @@ -11,4 +14,4 @@ "tsx": true } } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-4xxx/4314/1/output/input.js b/crates/swc/tests/fixture/issues-4xxx/4314/1/output/input.js index 654330231e8e..d57c2682eb64 100644 --- a/crates/swc/tests/fixture/issues-4xxx/4314/1/output/input.js +++ b/crates/swc/tests/fixture/issues-4xxx/4314/1/output/input.js @@ -1,6 +1,9 @@ -/*#__PURE__*/ React.createElement(Wrapper, null, /*#__PURE__*/ React.createElement(Sidebar, { - author: { - name: author.name, - function: author.function - } -})); +/*#__PURE__*/ const { jsx: _jsx } = require("react/jsx-runtime"); +_jsx(Wrapper, { + children: /*#__PURE__*/ _jsx(Sidebar, { + author: { + name: author.name, + function: author.function + } + }) +}); diff --git a/crates/swc/tests/fixture/issues-4xxx/4314/2/output/input.js b/crates/swc/tests/fixture/issues-4xxx/4314/2/output/input.js index 22744c3fbdda..6f9cd52ad8f2 100644 --- a/crates/swc/tests/fixture/issues-4xxx/4314/2/output/input.js +++ b/crates/swc/tests/fixture/issues-4xxx/4314/2/output/input.js @@ -1,10 +1,11 @@ -/*#__PURE__*/ React.createElement(C, { +/*#__PURE__*/ const { jsx: _jsx } = require("react/jsx-runtime"); +_jsx(C, { a: { a: 1, function: /r/ } }); -/*#__PURE__*/ React.createElement(C, { +/*#__PURE__*/ _jsx(C, { a: { a: 1, function: function() { @@ -12,7 +13,7 @@ } } }); -/*#__PURE__*/ React.createElement(C, { +/*#__PURE__*/ _jsx(C, { function: { a: 1, function: /r/ diff --git a/crates/swc/tests/fixture/issues-6xxx/6984/1/output/index.js b/crates/swc/tests/fixture/issues-6xxx/6984/1/output/index.js index 106e15329c85..5f8fcb84bf34 100644 --- a/crates/swc/tests/fixture/issues-6xxx/6984/1/output/index.js +++ b/crates/swc/tests/fixture/issues-6xxx/6984/1/output/index.js @@ -3,6 +3,7 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; import { _ as _create_class } from "@swc/helpers/_/_create_class"; import { _ as _inherits } from "@swc/helpers/_/_inherits"; import { _ as _ts_decorate } from "@swc/helpers/_/_ts_decorate"; +import { jsx as _jsx } from "react/jsx-runtime"; import React from 'react'; import { withRouter } from 'react-router-dom'; var App = /*#__PURE__*/ function(_React_Component) { @@ -17,7 +18,9 @@ var App = /*#__PURE__*/ function(_React_Component) { key: "render", value: function render() { console.log(this.props); - return React.createElement("div", null, "134"); + return _jsx("div", { + children: "134" + }); } } ]); diff --git a/crates/swc/tests/fixture/issues-7xxx/7539/input/index.js b/crates/swc/tests/fixture/issues-7xxx/7539/input/index.js index 27ad390aca3b..b1fc0c015728 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7539/input/index.js +++ b/crates/swc/tests/fixture/issues-7xxx/7539/input/index.js @@ -1,3 +1,4 @@ +/* #jscRuntime classic */ /* @jsx h */ /* @jsxFrag null */ <>; \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-7xxx/7539/output/index.js b/crates/swc/tests/fixture/issues-7xxx/7539/output/index.js index 2c1488f43228..b612aa32a428 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7539/output/index.js +++ b/crates/swc/tests/fixture/issues-7xxx/7539/output/index.js @@ -1 +1,2 @@ -/* @jsx h */ /* @jsxFrag null */ /*#__PURE__*/ h(null, null); +/* #jscRuntime classic */ /* @jsx h */ /* @jsxFrag null */ /*#__PURE__*/ var _require = require("react/jsx-runtime"), _jsx = _require.jsx, _Fragment = _require.Fragment; +_jsx(_Fragment, {}); diff --git a/crates/swc/tests/fixture/issues-7xxx/7653/output/1.js b/crates/swc/tests/fixture/issues-7xxx/7653/output/1.js index 0e2994b7a910..47316e064a4c 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7653/output/1.js +++ b/crates/swc/tests/fixture/issues-7xxx/7653/output/1.js @@ -1 +1 @@ -export default function Home(){return React.createElement("div",{dangerouslySetInnerHTML:{__html:"Hello World"}})} +import{jsx as _jsx}from"react/jsx-runtime";export default function Home(){return _jsx("div",{dangerouslySetInnerHTML:{__html:"Hello World"}})} diff --git a/crates/swc/tests/fixture/issues-7xxx/7700/output/1.js b/crates/swc/tests/fixture/issues-7xxx/7700/output/1.js index fed84e8eb807..1b8487ed9c23 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7700/output/1.js +++ b/crates/swc/tests/fixture/issues-7xxx/7700/output/1.js @@ -1,3 +1,4 @@ +import { jsxs as _jsxs } from "react/jsx-runtime"; let positions = { top: 1, left: 2, @@ -10,6 +11,10 @@ let positions = { bottom: 4 }; export function PositionRender({ isRtl, position }) { - let display = ('fe-fe-fe' === isRtl ? rtlPositions : positions)[position]; - return React.createElement("h1", null, "PositionRender: ", display); + return _jsxs("h1", { + children: [ + "PositionRender: ", + ('fe-fe-fe' === isRtl ? rtlPositions : positions)[position] + ] + }); } diff --git a/crates/swc/tests/fixture/issues-7xxx/7700/output/2.js b/crates/swc/tests/fixture/issues-7xxx/7700/output/2.js index 83f8f8d3417f..f745dffd0bfa 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7700/output/2.js +++ b/crates/swc/tests/fixture/issues-7xxx/7700/output/2.js @@ -1,3 +1,4 @@ +import { jsxs as _jsxs } from "react/jsx-runtime"; let positions = { top: 1, left: 2, @@ -10,10 +11,14 @@ let positions = { bottom: 4 }; export function PositionRender({ isRtl, position }) { - let display = ('fe-fe-fe' === isRtl ? [ - rtlPositions - ] : { - positions - })[position]; - return React.createElement("h1", null, "PositionRender: ", display); + return _jsxs("h1", { + children: [ + "PositionRender: ", + ('fe-fe-fe' === isRtl ? [ + rtlPositions + ] : { + positions + })[position] + ] + }); } diff --git a/crates/swc/tests/fixture/issues-7xxx/7700/output/3.js b/crates/swc/tests/fixture/issues-7xxx/7700/output/3.js index 23372fc464ec..46d9a13e463d 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7700/output/3.js +++ b/crates/swc/tests/fixture/issues-7xxx/7700/output/3.js @@ -1,3 +1,4 @@ +import { jsxs as _jsxs } from "react/jsx-runtime"; let positions = { top: 1, left: 2, @@ -10,10 +11,14 @@ let positions = { bottom: 4 }; export function PositionRender({ isRtl, position }) { - let display = ('fe-fe-fe' === isRtl ? [ - rtlPositions ?? 1 - ] : { - positions - })[position]; - return React.createElement("h1", null, "PositionRender: ", display); + return _jsxs("h1", { + children: [ + "PositionRender: ", + ('fe-fe-fe' === isRtl ? [ + rtlPositions ?? 1 + ] : { + positions + })[position] + ] + }); } diff --git a/crates/swc/tests/fixture/issues-7xxx/7700/output/4.js b/crates/swc/tests/fixture/issues-7xxx/7700/output/4.js index 034a68fe7954..bd7f72493f00 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7700/output/4.js +++ b/crates/swc/tests/fixture/issues-7xxx/7700/output/4.js @@ -1,3 +1,4 @@ +import { jsxs as _jsxs } from "react/jsx-runtime"; let positions = { top: 1, left: 2, @@ -10,8 +11,12 @@ let positions = { bottom: 4 }; export function PositionRender({ isRtl, position }) { - let display = ('fe-fe-fe' === isRtl ? rtlPositions : { - a: positions - })[position]; - return React.createElement("h1", null, "PositionRender: ", display); + return _jsxs("h1", { + children: [ + "PositionRender: ", + ('fe-fe-fe' === isRtl ? rtlPositions : { + a: positions + })[position] + ] + }); } diff --git a/crates/swc/tests/fixture/issues-7xxx/7700/output/5.js b/crates/swc/tests/fixture/issues-7xxx/7700/output/5.js index 49f36e4e4ee8..ceda74712ce2 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7700/output/5.js +++ b/crates/swc/tests/fixture/issues-7xxx/7700/output/5.js @@ -1,3 +1,4 @@ +import { jsxs as _jsxs } from "react/jsx-runtime"; let positions = { top: 1, left: 2, @@ -10,10 +11,14 @@ let positions = { bottom: 4 }; export function PositionRender({ isRtl, position }) { - let display = ('fe-fe-fe' === isRtl ? rtlPositions : { - a: [ - positions + return _jsxs("h1", { + children: [ + "PositionRender: ", + ('fe-fe-fe' === isRtl ? rtlPositions : { + a: [ + positions + ] + })[position] ] - })[position]; - return React.createElement("h1", null, "PositionRender: ", display); + }); } diff --git a/crates/swc/tests/fixture/issues-7xxx/7783/output/1.js b/crates/swc/tests/fixture/issues-7xxx/7783/output/1.js index 58d2bed8bc9b..28bf7440c143 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7783/output/1.js +++ b/crates/swc/tests/fixture/issues-7xxx/7783/output/1.js @@ -1 +1 @@ -export default function e(){return React.createElement("div",null,foo.a)}let foo={get a(){return`a ${this.b}`},get b(){return"b"}}; +import{jsx as t}from"react/jsx-runtime";export default function r(){return t("div",{children:foo.a})}let foo={get a(){return`a ${this.b}`},get b(){return"b"}}; diff --git a/crates/swc/tests/fixture/issues-7xxx/7821/output/1.js b/crates/swc/tests/fixture/issues-7xxx/7821/output/1.js index 959d81130675..2d10f7faec8f 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7821/output/1.js +++ b/crates/swc/tests/fixture/issues-7xxx/7821/output/1.js @@ -1,19 +1,24 @@ +import { jsx as r, Fragment as n } from "react/jsx-runtime"; var Blocks = { Block1: function() { - return React.createElement(React.Fragment, null, "'Block1xx'"); + return r(n, { + children: "'Block1xx'" + }); }, Block2: function() { - return React.createElement(React.Fragment, null, "'Block2xx'"); + return r(n, { + children: "'Block2xx'" + }); }, Layout1: function() { - var e; - return e = Blocks, [ + var r; + return r = Blocks, [ 'Block1' - ].map(function(t) { - return e[t]; + ].map(function(n) { + return r[n]; }); } }; export function render() { - return React.createElement(Blocks.Layout1, null); + return r(Blocks.Layout1, {}); } diff --git a/crates/swc/tests/fixture/issues-8xxx/8184/1/input/.swcrc b/crates/swc/tests/fixture/issues-8xxx/8184/1/input/.swcrc index f114fa4de9d5..cb687f9f6714 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8184/1/input/.swcrc +++ b/crates/swc/tests/fixture/issues-8xxx/8184/1/input/.swcrc @@ -9,6 +9,11 @@ "~/*": [ "./src/*" ] + }, + "transform": { + "react": { + "runtime": "classic" + } } } } \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-8xxx/8210/input/.swcrc b/crates/swc/tests/fixture/issues-8xxx/8210/input/.swcrc index 53722f9ac21b..68a3a111ce37 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8210/input/.swcrc +++ b/crates/swc/tests/fixture/issues-8xxx/8210/input/.swcrc @@ -11,10 +11,7 @@ "mangle": false }, "transform": { - "react": { - "development": true, - "runtime": "automatic" - } + "react": "react-jsxdev" } }, "module": { diff --git a/crates/swc/tests/fixture/issues-8xxx/8210/output/1.js b/crates/swc/tests/fixture/issues-8xxx/8210/output/1.js index ea1bbedd0ad5..50d292db91b8 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8210/output/1.js +++ b/crates/swc/tests/fixture/issues-8xxx/8210/output/1.js @@ -5,7 +5,7 @@ const Component = ()=>{ fileName: "$DIR/tests/fixture/issues-8xxx/8210/input/1.js", lineNumber: 2, columnNumber: 23 - }, void 0), + }, this), children: "Hello" }, void 0, false, { fileName: "$DIR/tests/fixture/issues-8xxx/8210/input/1.js", diff --git a/crates/swc/tests/fixture/issues-8xxx/8528/input/.swcrc b/crates/swc/tests/fixture/issues-8xxx/8528/input/.swcrc index 3b01d7ddcd9e..b404afc90ba7 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8528/input/.swcrc +++ b/crates/swc/tests/fixture/issues-8xxx/8528/input/.swcrc @@ -5,7 +5,10 @@ "syntax": "typescript" }, "transform": { - "decoratorVersion": "2022-03" + "decoratorVersion": "2022-03", + "react": { + "runtime": "classic" + } }, "externalHelpers": true, "experimental": { diff --git a/crates/swc/tests/fixture/issues-8xxx/8594/input/.swcrc b/crates/swc/tests/fixture/issues-8xxx/8594/input/.swcrc index 63a04f741e14..c66d5a22cc1d 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8594/input/.swcrc +++ b/crates/swc/tests/fixture/issues-8xxx/8594/input/.swcrc @@ -9,6 +9,11 @@ "minify": { "compress": false, "mangle": false + }, + "transform": { + "react": { + "runtime": "classic" + } } }, "module": { diff --git a/crates/swc/tests/fixture/issues-8xxx/8640/output/index.tsx b/crates/swc/tests/fixture/issues-8xxx/8640/output/index.tsx index c7d94d8591b1..010a305f5cba 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8640/output/index.tsx +++ b/crates/swc/tests/fixture/issues-8xxx/8640/output/index.tsx @@ -1,6 +1,7 @@ +import { jsx as _jsx } from "react/jsx-runtime"; import * as React from 'react'; (function(Ns) { Ns.Context = React.createContext(); - Ns.Component = ()=>React.createElement(Ns.Context.Provider, null); + Ns.Component = ()=>_jsx(Ns.Context.Provider, {}); })(Ns || (Ns = {})); export var Ns; diff --git a/crates/swc/tests/fixture/issues-8xxx/8935/output/src/button.jsx b/crates/swc/tests/fixture/issues-8xxx/8935/output/src/button.jsx index 311147c2df7f..c5d077cd6079 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8935/output/src/button.jsx +++ b/crates/swc/tests/fixture/issues-8xxx/8935/output/src/button.jsx @@ -1,6 +1,8 @@ +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import { jsx as _jsx } from "react/jsx-runtime"; export function Button(props) { - return /*#__PURE__*/ React.createElement("button", props); + return /*#__PURE__*/ _jsx("button", _object_spread({}, props)); } export function Button(props) { - return /*#__PURE__*/ React.createElement("button", props); + return /*#__PURE__*/ _jsx("button", _object_spread({}, props)); } diff --git a/crates/swc/tests/fixture/issues-9xxx/9204/output/1.js b/crates/swc/tests/fixture/issues-9xxx/9204/output/1.js index 1c3d2c217274..5e681dd4b26d 100644 --- a/crates/swc/tests/fixture/issues-9xxx/9204/output/1.js +++ b/crates/swc/tests/fixture/issues-9xxx/9204/output/1.js @@ -1,4 +1,7 @@ +import { jsx as _jsx } from "react/jsx-runtime"; let Foo = createFoo(); export function App() { - return React.createElement("view", null, React.createElement(Foo, null)); + return _jsx("view", { + children: _jsx(Foo, {}) + }); } diff --git a/crates/swc/tests/fixture/issues-9xxx/9394/output/index.tsx b/crates/swc/tests/fixture/issues-9xxx/9394/output/index.tsx index 83c1d6f88a0b..94c583891a11 100644 --- a/crates/swc/tests/fixture/issues-9xxx/9394/output/index.tsx +++ b/crates/swc/tests/fixture/issues-9xxx/9394/output/index.tsx @@ -1,7 +1,8 @@ +const { jsx: _jsx } = require("react/jsx-runtime"); class MyClass { myNumber; constructor(myNumber){ this.myNumber = myNumber; - const component = /*#__PURE__*/ React.createElement(MyComponent, null); + const component = /*#__PURE__*/ _jsx(MyComponent, {}); } } diff --git a/crates/swc/tests/fixture/issues-9xxx/9685/output/index.tsx b/crates/swc/tests/fixture/issues-9xxx/9685/output/index.tsx index 3f7f9480bc18..c3e83cea4fe0 100644 --- a/crates/swc/tests/fixture/issues-9xxx/9685/output/index.tsx +++ b/crates/swc/tests/fixture/issues-9xxx/9685/output/index.tsx @@ -1,5 +1,6 @@ +import { jsx as _jsx } from "react/jsx-runtime"; (function(form) { form.input = null; - form.test = /*#__PURE__*/ React.createElement("input", null); + form.test = /*#__PURE__*/ _jsx("input", {}); })(form || (form = {})); export var form; diff --git a/crates/swc/tests/fixture/next.js/server/render/1/input/.swcrc b/crates/swc/tests/fixture/next.js/server/render/1/input/.swcrc index 7321a83c759e..e84a65e90af0 100644 --- a/crates/swc/tests/fixture/next.js/server/render/1/input/.swcrc +++ b/crates/swc/tests/fixture/next.js/server/render/1/input/.swcrc @@ -4,6 +4,11 @@ "parser": { "syntax": "typescript", "tsx": true + }, + "transform": { + "react": { + "runtime": "classic" + } } } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/shopify/001/input/.swcrc b/crates/swc/tests/fixture/shopify/001/input/.swcrc index ca814d7caad1..48dcc6999dfa 100644 --- a/crates/swc/tests/fixture/shopify/001/input/.swcrc +++ b/crates/swc/tests/fixture/shopify/001/input/.swcrc @@ -3,9 +3,14 @@ "parser": { "syntax": "ecmascript", "jsx": true + }, + "transform": { + "react": { + "runtime": "classic" + } } }, "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/shopify/002/input/.swcrc b/crates/swc/tests/fixture/shopify/002/input/.swcrc index ca814d7caad1..48dcc6999dfa 100644 --- a/crates/swc/tests/fixture/shopify/002/input/.swcrc +++ b/crates/swc/tests/fixture/shopify/002/input/.swcrc @@ -3,9 +3,14 @@ "parser": { "syntax": "ecmascript", "jsx": true + }, + "transform": { + "react": { + "runtime": "classic" + } } }, "module": { "type": "commonjs" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/shopify/003-env/input/.swcrc b/crates/swc/tests/fixture/shopify/003-env/input/.swcrc index da31bdae1b1b..beb4e7dae085 100644 --- a/crates/swc/tests/fixture/shopify/003-env/input/.swcrc +++ b/crates/swc/tests/fixture/shopify/003-env/input/.swcrc @@ -3,6 +3,11 @@ "parser": { "syntax": "ecmascript", "jsx": true + }, + "transform": { + "react": { + "runtime": "classic" + } } }, "module": { @@ -11,4 +16,4 @@ "env": { "chrome": "50" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/shopify/004-jest/input/.swcrc b/crates/swc/tests/fixture/shopify/004-jest/input/.swcrc index 4cb82f415a7a..836e932b0fa5 100644 --- a/crates/swc/tests/fixture/shopify/004-jest/input/.swcrc +++ b/crates/swc/tests/fixture/shopify/004-jest/input/.swcrc @@ -7,6 +7,9 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } } }, @@ -16,4 +19,4 @@ "env": { "chrome": "50" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/shopify/005-no-module/input/.swcrc b/crates/swc/tests/fixture/shopify/005-no-module/input/.swcrc index f2c8ed0408cc..a661b14942e0 100644 --- a/crates/swc/tests/fixture/shopify/005-no-module/input/.swcrc +++ b/crates/swc/tests/fixture/shopify/005-no-module/input/.swcrc @@ -7,10 +7,13 @@ "transform": { "hidden": { "jest": true + }, + "react": { + "runtime": "classic" } } }, "env": { "chrome": "50" } -} +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/sourcemap/002/output/index.js b/crates/swc/tests/fixture/sourcemap/002/output/index.js index f0793c1e2a06..470f9efe110e 100644 --- a/crates/swc/tests/fixture/sourcemap/002/output/index.js +++ b/crates/swc/tests/fixture/sourcemap/002/output/index.js @@ -1,8 +1,11 @@ import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator"; import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator"; +import { jsx as _jsx } from "react/jsx-runtime"; export default function StaticPage(param) { var data = param.data; - return /*#__PURE__*/ React.createElement("div", null, data.foo); + return /*#__PURE__*/ _jsx("div", { + children: data.foo + }); } export function getStaticProps() { return _async_to_generator(function() { diff --git a/crates/swc/tests/fixture/sourcemap/002/output/index.map b/crates/swc/tests/fixture/sourcemap/002/output/index.map index 4f04b49733f2..e092b29d0b01 100644 --- a/crates/swc/tests/fixture/sourcemap/002/output/index.map +++ b/crates/swc/tests/fixture/sourcemap/002/output/index.map @@ -1,5 +1,5 @@ { - "mappings": ";;AAAA,eAAe,SAASA,WAAW,KAAQ;QAAR,AAAEC,OAAF,MAAEA;IACjC,qBAAO,oBAACC,aAAKD,KAAKE,GAAG;AACzB;AAEA,OAAO,SAAeC;;;YAClB;;gBAAO;oBACHC,OAAO;wBACHJ,MAAM;4BACFE,KAAK;wBACT;oBACJ;gBACJ;;;IACJ", + "mappings": ";;;AAAA,eAAe,SAASA,WAAW,KAAQ;QAAR,AAAEC,OAAF,MAAEA;IACjC,qBAAO,KAACC;kBAAKD,KAAKE,GAAG;;AACzB;AAEA,OAAO,SAAeC;;;YAClB;;gBAAO;oBACHC,OAAO;wBACHJ,MAAM;4BACFE,KAAK;wBACT;oBACJ;gBACJ;;;IACJ", "names": [ "StaticPage", "data", diff --git a/crates/swc/tests/fixture/sourcemap/003/output/index.js b/crates/swc/tests/fixture/sourcemap/003/output/index.js index 3a90f442088b..6c89eea36140 100644 --- a/crates/swc/tests/fixture/sourcemap/003/output/index.js +++ b/crates/swc/tests/fixture/sourcemap/003/output/index.js @@ -1 +1 @@ -import{_ as t}from"@swc/helpers/_/_async_to_generator";import{_ as r}from"@swc/helpers/_/_ts_generator";export default function e(t){var r=t.data;return React.createElement("div",null,r.foo)}export function getStaticProps(){return t(function(){return r(this,function(t){return[2,{props:{data:{foo:"bar"}}}]})})()} +import{_ as r}from"@swc/helpers/_/_async_to_generator";import{_ as t}from"@swc/helpers/_/_ts_generator";import{jsx as o}from"react/jsx-runtime";export default function e(r){return o("div",{children:r.data.foo})}export function getStaticProps(){return r(function(){return t(this,function(r){return[2,{props:{data:{foo:"bar"}}}]})})()} diff --git a/crates/swc/tests/fixture/sourcemap/003/output/index.map b/crates/swc/tests/fixture/sourcemap/003/output/index.map index 275fe2ed82e3..d66060e60320 100644 --- a/crates/swc/tests/fixture/sourcemap/003/output/index.map +++ b/crates/swc/tests/fixture/sourcemap/003/output/index.map @@ -1,9 +1,9 @@ { - "mappings": "uGAAA,gBAAe,SAASA,EAAW,CAAQ,MAAR,AAAEC,EAAF,EAAEA,KACjC,OAAO,oBAACC,WAAKD,EAAKE,GAAG,CACzB,CAEA,OAAO,SAAeC,+DAClB,SAAO,CACHC,MAAO,CACHJ,KAAM,CACFE,IAAK,KACT,CACJ,CACJ,IACJ", + "mappings": "+IAAA,gBAAe,SAASA,EAAW,CAAQ,EACvC,OAAO,EAACC,gBAAKC,AADkB,EAAEA,KACfC,GAAG,EACzB,CAEA,OAAO,SAAeC,+DAClB,SAAO,CACHC,MAAO,CACHH,KAAM,CACFC,IAAK,KACT,CACJ,CACJ,IACJ", "names": [ "StaticPage", - "data", "div", + "data", "foo", "getStaticProps", "props" diff --git a/crates/swc/tests/projects/issue-351/input.js b/crates/swc/tests/projects/issue-351/input.js index 7f5fd01a315c..f9213a7f35e9 100644 --- a/crates/swc/tests/projects/issue-351/input.js +++ b/crates/swc/tests/projects/issue-351/input.js @@ -1,3 +1,4 @@ +// @jsxRuntime classic import React from 'react';
; \ No newline at end of file diff --git a/crates/swc/tests/rust_api.rs b/crates/swc/tests/rust_api.rs index c952b36a2573..d9de59d93dfe 100644 --- a/crates/swc/tests/rust_api.rs +++ b/crates/swc/tests/rust_api.rs @@ -66,6 +66,7 @@ fn shopify_1_check_filename() { let fm = cm.new_source_file( FileName::Anon.into(), " + // @jsxRuntime classic import React from 'react'; import { useI18n } from '@shopify/react-i18n'; @@ -164,6 +165,7 @@ fn shopify_2_same_opt() { let fm = cm.new_source_file( FileName::Real("/Users/kdy1/projects/example-swcify/src/App/App.tsx".into()).into(), " + // @jsxRuntime classic import React from 'react'; import { useI18n } from '@shopify/react-i18n'; @@ -231,6 +233,7 @@ fn shopify_3_reduce_defaults() { let fm = cm.new_source_file( FileName::Real("/Users/kdy1/projects/example-swcify/src/App/App.tsx".into()).into(), " + // @jsxRuntime classic import React from 'react'; import { useI18n } from '@shopify/react-i18n'; @@ -293,6 +296,7 @@ fn shopify_4_reduce_more() { let fm = cm.new_source_file( FileName::Real("/Users/kdy1/projects/example-swcify/src/App/App.tsx".into()).into(), " + // @jsxRuntime classic import React from 'react'; import { useI18n } from '@shopify/react-i18n'; diff --git a/crates/swc/tests/simple.rs b/crates/swc/tests/simple.rs index 660d4a1cd5b7..d26596713383 100644 --- a/crates/swc/tests/simple.rs +++ b/crates/swc/tests/simple.rs @@ -86,7 +86,8 @@ fn issue_834_3() { fn test_tsx_escape_xhtml() { let source = r#"
"#; - let expected = r#"/*#__PURE__*/ React.createElement("div", { + let expected = r#"/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { id: "abc>" }); "#; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.1.normal.js index cec7e7afa10b..793609dec9db 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.1.normal.js @@ -1,10 +1,12 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface Prop { -//! 5 | a: number, -//! `---- +function Comp(p) { + return
{p.b}
; +} +// OK +var k = ; +var k1 = + hi hi hi! + ; +var k2 = +
hi hi hi!
+
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.2.minified.js index cec7e7afa10b..1663266c069a 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty1.2.minified.js @@ -1,10 +1,9 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface Prop { -//! 5 | a: number, -//! `---- +function Comp(p) { + return
{p.b}
; +} +, + hi hi hi! + , +
hi hi hi!
+
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.1.normal.js index 2c3e9ef014a5..27cd00631af9 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.1.normal.js @@ -7,14 +7,14 @@ var Button = /*#__PURE__*/ function() { } var _proto = Button.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement("div", null, "My Button"); + return
My Button
; }; return Button; }(); // OK -var k1 = /*#__PURE__*/ React.createElement("div", null, " ", /*#__PURE__*/ React.createElement("h2", null, " Hello "), " ", /*#__PURE__*/ React.createElement("h1", null, " world ")); -var k2 = /*#__PURE__*/ React.createElement("div", null, " ", /*#__PURE__*/ React.createElement("h2", null, " Hello "), " ", function(user) { - return /*#__PURE__*/ React.createElement("h2", null, user.name); -}); -var k3 = /*#__PURE__*/ React.createElement("div", null, " ", 1, " ", "That is a number", " "); -var k4 = /*#__PURE__*/ React.createElement(Button, null, " ", /*#__PURE__*/ React.createElement("h2", null, " Hello "), " "); +var k1 =

Hello

world

; +var k2 =

Hello

{function(user) { + return

{user.name}

; +}}
; +var k3 =
{1} {"That is a number"}
; +var k4 = ; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.2.minified.js index 8747e15e8112..9a01d415bae1 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty10.2.minified.js @@ -1,2 +1,13 @@ //// [file.tsx] -import "@swc/helpers/_/_class_call_check"; +import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; +var Button = /*#__PURE__*/ function() { + function Button() { + _class_call_check(this, Button); + } + return Button.prototype.render = function() { + return
My Button
; + }, Button; +}(); +

Hello

world

,

Hello

{function(user) { + return

{user.name}

; +}}
,
{1} {"That is a number"}
, ; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.1.normal.js index 2c3e9ef014a5..27cd00631af9 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.1.normal.js @@ -7,14 +7,14 @@ var Button = /*#__PURE__*/ function() { } var _proto = Button.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement("div", null, "My Button"); + return
My Button
; }; return Button; }(); // OK -var k1 = /*#__PURE__*/ React.createElement("div", null, " ", /*#__PURE__*/ React.createElement("h2", null, " Hello "), " ", /*#__PURE__*/ React.createElement("h1", null, " world ")); -var k2 = /*#__PURE__*/ React.createElement("div", null, " ", /*#__PURE__*/ React.createElement("h2", null, " Hello "), " ", function(user) { - return /*#__PURE__*/ React.createElement("h2", null, user.name); -}); -var k3 = /*#__PURE__*/ React.createElement("div", null, " ", 1, " ", "That is a number", " "); -var k4 = /*#__PURE__*/ React.createElement(Button, null, " ", /*#__PURE__*/ React.createElement("h2", null, " Hello "), " "); +var k1 =

Hello

world

; +var k2 =

Hello

{function(user) { + return

{user.name}

; +}}
; +var k3 =
{1} {"That is a number"}
; +var k4 = ; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.2.minified.js index 8747e15e8112..9a01d415bae1 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty11.2.minified.js @@ -1,2 +1,13 @@ //// [file.tsx] -import "@swc/helpers/_/_class_call_check"; +import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; +var Button = /*#__PURE__*/ function() { + function Button() { + _class_call_check(this, Button); + } + return Button.prototype.render = function() { + return
My Button
; + }, Button; +}(); +

Hello

world

,

Hello

{function(user) { + return

{user.name}

; +}}
,
{1} {"That is a number"}
, ; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.1.normal.js index 248f2248e56e..da40fa53cb60 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.1.normal.js @@ -1,9 +1,11 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | const Tag = (x: {}) =>
; -//! `---- +var Tag = function(x) { + return
; +}; +// OK +var k1 = ; +var k2 = ; +// Not OK (excess children) +var k3 =
}/>; +var k4 =
; +var k5 =
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.2.minified.js index 248f2248e56e..a077925e1324 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty15.2.minified.js @@ -1,9 +1,5 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | const Tag = (x: {}) =>
; -//! `---- +var Tag = function(x) { + return
; +}; +, ,
}/>,
,
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.1.normal.js index 3e8b0f6190f2..d76e2de3ff44 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.1.normal.js @@ -1,12 +1,12 @@ //// [checkJsxChildrenProperty16.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[6:1] -//! 3 | -//! 4 | // repro from #53493 -//! 5 | -//! 6 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 7 | -//! 8 | export type Props = -//! 9 | | { renderNumber?: false; children: (arg: string) => void } -//! `---- +/// +// repro from #53493 +export var Test = function() { + return <> + {function(value) {}} + {function(value) {}} + + + + ; +}; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.2.minified.js index 3e8b0f6190f2..470c5172e1d8 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty16.2.minified.js @@ -1,12 +1,10 @@ //// [checkJsxChildrenProperty16.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[6:1] -//! 3 | -//! 4 | // repro from #53493 -//! 5 | -//! 6 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 7 | -//! 8 | export type Props = -//! 9 | | { renderNumber?: false; children: (arg: string) => void } -//! `---- +export var Test = function() { + return <> + {function(value) {}} + {function(value) {}} + + + + ; +}; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.1.normal.js index cec7e7afa10b..444ba09462db 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.1.normal.js @@ -1,10 +1,34 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface Prop { -//! 5 | a: number, -//! `---- +function Comp(p) { + return
{p.b}
; +} +// Error: missing children +var k = ; +var k0 = + hi hi hi! + ; +var o = { + children: "Random" +}; +var k1 = + hi hi hi! + ; +// Error: incorrect type +var k2 = +
My Div
+ {function(name) { + return
My name {name}
; +}} +
; +var k3 = +
My Div
+ {1000000} +
; +var k4 = +
My Div
+ hi hi hi! +
; +var k5 = +
My Div
+
My Div
+
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.2.minified.js index cec7e7afa10b..f92f8b477ff1 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty2.2.minified.js @@ -1,10 +1,25 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface Prop { -//! 5 | a: number, -//! `---- +function Comp(p) { + return
{p.b}
; +} +, + hi hi hi! + , + hi hi hi! + , +
My Div
+ {function(name) { + return
My name {name}
; +}} +
, +
My Div
+ {1000000} +
, +
My Div
+ hi hi hi! +
, +
My Div
+
My Div
+
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.1.normal.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.1.normal.js index 0daaf4992bf8..0ee5799b1238 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.1.normal.js @@ -1,10 +1,7 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | // OK -//! 5 | let k1 =

Hello

world

; -//! `---- +// OK +var k1 =

Hello

world

; +var k2 =

Hello

{function(user) { + return

{user.name}

; +}}
; +var k3 =
{1} {"That is a number"}
; diff --git a/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.2.minified.js b/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.2.minified.js index 0daaf4992bf8..5b91e88eed11 100644 --- a/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxChildrenProperty9.2.minified.js @@ -1,10 +1,4 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | // OK -//! 5 | let k1 =

Hello

world

; -//! `---- +

Hello

world

,

Hello

{function(user) { + return

{user.name}

; +}}
,
{1} {"That is a number"}
; diff --git a/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.1.normal.js b/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.1.normal.js index 3d0a06f95729..0721bf02e0d8 100644 --- a/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.1.normal.js @@ -1,34 +1,22 @@ //// [file.tsx] import * as React from "react"; -var a = /*#__PURE__*/ React.createElement(GenericComponent, { - initialValues: { - x: "y" - }, - nextValues: function(a) { - return a; - } -}); // No error -var b = /*#__PURE__*/ React.createElement(GenericComponent, { - initialValues: 12, - nextValues: function(a) { - return a; - } -}); // No error - Values should be reinstantiated with `number` (since `object` is a default, not a constraint) -var c = /*#__PURE__*/ React.createElement(GenericComponent, { - initialValues: { - x: "y" - }, - nextValues: function(a) { - return { - x: a.x - }; - } -}); // No Error -var d = /*#__PURE__*/ React.createElement(GenericComponent, { - initialValues: { - x: "y" - }, - nextValues: function(a) { - return a.x; - } -}); // Error - `string` is not assignable to `{x: string}` +var a = ; // No error +var b = ; // No error - Values should be reinstantiated with `number` (since `object` is a default, not a constraint) +var c = ; // No Error +var d = ; // Error - `string` is not assignable to `{x: string}` diff --git a/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.2.minified.js b/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.2.minified.js index 9057077daa78..0e01c541bbaf 100644 --- a/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxGenericTagHasCorrectInferences.2.minified.js @@ -1,3 +1,19 @@ //// [file.tsx] import "react"; -GenericComponent, GenericComponent, GenericComponent, GenericComponent; +, , , ; diff --git a/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.1.normal.js b/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.1.normal.js index 10e9e2718219..5afa4fa6e35b 100644 --- a/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.1.normal.js +++ b/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.1.normal.js @@ -14,6 +14,4 @@ var C = /*#__PURE__*/ function(Component1) { var y = new C({ foobar: "example" }); -var x = /*#__PURE__*/ React.createElement(C, { - foobar: "example" -}); +var x = ; diff --git a/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.2.minified.js b/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.2.minified.js index 5ccfd00a8e24..e816c8f1ba7e 100644 --- a/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.2.minified.js +++ b/crates/swc/tests/tsc-references/checkJsxIntersectionElementPropsType.2.minified.js @@ -2,11 +2,12 @@ import { _ as _call_super } from "@swc/helpers/_/_call_super"; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; import { _ as _inherits } from "@swc/helpers/_/_inherits"; -new (/*#__PURE__*/ function(Component1) { +var C = /*#__PURE__*/ function(Component1) { function C() { return _class_call_check(this, C), _call_super(this, C, arguments); } return _inherits(C, Component1), C; -}(Component))({ +}(Component); +new C({ foobar: "example" -}); +}), ; diff --git a/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.1.normal.js b/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.1.normal.js index bd1996ac069f..8c77c22f376f 100644 --- a/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.1.normal.js +++ b/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.1.normal.js @@ -1,10 +1,20 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 |
-//! 5 | // Not Comment -//! `---- +
+ // Not Comment +
; +
+ // Not Comment + {} + // Another not Comment +
; +
+ // Not Comment + {//Comment just Fine +"Hi"} + // Another not Comment +
; +
+ /* Not Comment */ + {//Comment just Fine +"Hi"} +
; diff --git a/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.2.minified.js b/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.2.minified.js index bd1996ac069f..0bb7f58a2a08 100644 --- a/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.2.minified.js +++ b/crates/swc/tests/tsc-references/commentEmittingInPreserveJsx1.2.minified.js @@ -1,10 +1,15 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 |
-//! 5 | // Not Comment -//! `---- +
+ // Not Comment +
,
+ // Not Comment + {} + // Another not Comment +
,
+ // Not Comment + {"Hi"} + // Another not Comment +
,
+ /* Not Comment */ + {"Hi"} +
; diff --git a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.1.normal.js b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.1.normal.js index 567b0d165d3e..bca133576a14 100644 --- a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.1.normal.js +++ b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.1.normal.js @@ -1,16 +1,8 @@ //// [contextuallyTypedStringLiteralsInJsxAttributes01.tsx] var FooComponent = function(props) { - return /*#__PURE__*/ React.createElement("span", null, props.foo); + return {props.foo}; }; -/*#__PURE__*/ React.createElement(FooComponent, { - foo: "A" -}); -/*#__PURE__*/ React.createElement(FooComponent, { - foo: "A" -}); -/*#__PURE__*/ React.createElement(FooComponent, { - foo: "f" -}); -/*#__PURE__*/ React.createElement(FooComponent, { - foo: "f" -}); +; +; +; +; diff --git a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.2.minified.js b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.2.minified.js index f76b6ca6eeac..e03589ffb77b 100644 --- a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.2.minified.js +++ b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes01.2.minified.js @@ -1 +1,5 @@ //// [contextuallyTypedStringLiteralsInJsxAttributes01.tsx] +var FooComponent = function(props) { + return {props.foo}; +}; +, , , ; diff --git a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.1.normal.js b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.1.normal.js index 12378b978e6c..0926a5506a26 100644 --- a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.1.normal.js +++ b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.1.normal.js @@ -1,9 +1,8 @@ //// [file.tsx] define([ "require", - "exports", - "react" -], function(require, exports, _react) { + "exports" +], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true @@ -32,40 +31,30 @@ define([ } return this._buildMainButton(props); } - var b0 = /*#__PURE__*/ _react.createElement(MainButton, { + var b0 = ; // k has type "left" | "right" + var b2 = ; // k has type "left" | "right" + var b3 = ; // goTo has type"home" | "contact" + var b4 = ; // goTo has type "home" | "contact" function NoOverload(buttonProps) { return undefined; } - var c1 = /*#__PURE__*/ _react.createElement(NoOverload, { + var c1 = ; // k has type any function NoOverload1(linkProps) { return undefined; } - var d1 = /*#__PURE__*/ _react.createElement(NoOverload1, { - goTo: "home", - extra: true - }); // goTo has type "home" | "contact" + var d1 = ; // goTo has type "home" | "contact" }); diff --git a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.2.minified.js b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.2.minified.js index 1a4ab8ee838a..27bc20ef09ea 100644 --- a/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.2.minified.js +++ b/crates/swc/tests/tsc-references/contextuallyTypedStringLiteralsInJsxAttributes02.2.minified.js @@ -1,9 +1,8 @@ //// [file.tsx] define([ "require", - "exports", - "react" -], function(require, exports, _react) { + "exports" +], function(require, exports) { Object.defineProperty(exports, "__esModule", { value: !0 }); @@ -27,4 +26,19 @@ define([ } function NoOverload(buttonProps) {} function NoOverload1(linkProps) {} + , , , , , ; }); diff --git a/crates/swc/tests/tsc-references/inlineJsxAndJsxFragPragma.1.normal.js b/crates/swc/tests/tsc-references/inlineJsxAndJsxFragPragma.1.normal.js index 6fb1d3d05119..4df68d84614a 100644 --- a/crates/swc/tests/tsc-references/inlineJsxAndJsxFragPragma.1.normal.js +++ b/crates/swc/tests/tsc-references/inlineJsxAndJsxFragPragma.1.normal.js @@ -31,7 +31,7 @@ export { }; /** * @jsx h * @jsxFrag Fragment - */ import { h, Fragment } from "./renderer"; + */ import { h } from "./renderer"; /*#__PURE__*/ h("div", null); //// [snabbdomy-no-fragment.tsx] /* @jsx jsx */ /* @jsxfrag null */ import { jsx } from "./renderer"; diff --git a/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.1.normal.js b/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.1.normal.js index 0f1df489db4b..af723f7999ac 100644 --- a/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.1.normal.js +++ b/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.1.normal.js @@ -1,11 +1,12 @@ //// [intraExpressionInferencesJsx.tsx] /// // repro from #52798 +import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; var Component = function(param) { var animations = param.animations, style = param.style; - return /*#__PURE__*/ React.createElement(React.Fragment, null); + return /*#__PURE__*/ _jsx(_Fragment, {}); }; -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ _jsx(Component, { animations: { test: { kind: "a", @@ -17,7 +18,7 @@ var Component = function(param) { return ""; } }); -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ _jsx(Component, { animations: { test: { kind: "a", @@ -34,7 +35,7 @@ var Component = function(param) { return ""; } }); -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ _jsx(Component, { animations: { test: { kind: "a", @@ -52,9 +53,9 @@ var Component = function(param) { } }); function Foo(props) { - return /*#__PURE__*/ React.createElement("div", null); + return /*#__PURE__*/ _jsx("div", {}); } -/*#__PURE__*/ React.createElement(Foo, { +/*#__PURE__*/ _jsx(Foo, { a: function() { return 10; }, @@ -62,7 +63,7 @@ function Foo(props) { arg.toString(); } }); -/*#__PURE__*/ React.createElement(Foo, { +/*#__PURE__*/ _jsx(Foo, { a: function(x) { return 10; }, @@ -70,7 +71,7 @@ function Foo(props) { arg.toString(); } }); -/*#__PURE__*/ React.createElement(Foo, { +/*#__PURE__*/ _jsx(Foo, { a: function(x) { return 10; }, diff --git a/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.2.minified.js b/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.2.minified.js index ee9743e644e9..206480b8d74d 100644 --- a/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.2.minified.js +++ b/crates/swc/tests/tsc-references/intraExpressionInferencesJsx.2.minified.js @@ -1 +1,2 @@ //// [intraExpressionInferencesJsx.tsx] +import "react/jsx-runtime"; diff --git a/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.1.normal.js b/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.1.normal.js index b048eb4cc3e8..adc2bc10b5b2 100644 --- a/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.1.normal.js @@ -2,8 +2,4 @@ import * as React from "react"; //// [file.jsx] import { MyComp } from "./component"; -import * as React from "react"; -var x = /*#__PURE__*/ React.createElement(MyComp, { - a: 10, - b: "hi" -}); // error, no type arguments in js +var x = ; // error, no type arguments in js diff --git a/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.2.minified.js b/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.2.minified.js index 99218a60d6d8..c924e8ff8103 100644 --- a/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxCheckJsxNoTypeArgumentsAllowed.2.minified.js @@ -1,5 +1,5 @@ //// [component.d.ts] import "react"; //// [file.jsx] -import "./component"; -import "react"; +import { MyComp } from "./component"; +; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..34935037264c --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx-dev.1.normal.js @@ -0,0 +1,14 @@ +//// [jsxJsxsCjsTransformChildren.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + children: "text" +}, void 0, false, { + fileName: "jsxJsxsCjsTransformChildren.tsx", + lineNumber: 2, + columnNumber: 11 +}, void 0); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..c06b8d67f418 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx-dev.2.minified.js @@ -0,0 +1,4 @@ +//// [jsxJsxsCjsTransformChildren.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}), require("react/jsx-dev-runtime"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx.1.normal.js similarity index 56% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren.1.normal.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx.1.normal.js index 3e386f35b7aa..135f93a9b92d 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx.1.normal.js @@ -4,4 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var a = /*#__PURE__*/ React.createElement("div", null, "text"); +var _jsxruntime = require("react/jsx-runtime"); +var a = /*#__PURE__*/ (0, _jsxruntime.jsx)("div", { + children: "text" +}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx.2.minified.js similarity index 74% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx.2.minified.js index a92af7bc3f94..6de5abccf937 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformChildren_react-jsx.2.minified.js @@ -1,4 +1,4 @@ //// [jsxJsxsCjsTransformChildren.tsx] Object.defineProperty(exports, "__esModule", { value: !0 -}); +}), require("react/jsx-runtime"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport.1.normal.js deleted file mode 100644 index fcf1cf1d5766..000000000000 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport.1.normal.js +++ /dev/null @@ -1,9 +0,0 @@ -//// [jsxJsxsCjsTransformCustomImport.tsx] -/// -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -var a = /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("p", null), "text", /*#__PURE__*/ React.createElement("div", { - className: "foo" -})); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..8d0a627c43ed --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx-dev.1.normal.js @@ -0,0 +1,49 @@ +//// [preact.tsx] +/// +/* @jsxImportSource preact */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)(_jsxdevruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("p", {}, void 0, false, { + fileName: "preact.tsx", + lineNumber: 4, + columnNumber: 3 + }, void 0), + "text", + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + className: "foo" + }, void 0, false, { + fileName: "preact.tsx", + lineNumber: 6, + columnNumber: 3 + }, void 0) + ] +}, void 0, true); +//// [react.tsx] +/// +/* @jsxImportSource react */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +require("./preact"); +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)(_jsxdevruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("p", {}, void 0, false, { + fileName: "react.tsx", + lineNumber: 5, + columnNumber: 3 + }, void 0), + "text", + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + className: "foo" + }, void 0, false, { + fileName: "react.tsx", + lineNumber: 7, + columnNumber: 3 + }, void 0) + ] +}, void 0, true); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..e0b9c159fe20 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx-dev.2.minified.js @@ -0,0 +1,10 @@ +//// [preact.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}), require("react/jsx-dev-runtime").Fragment; +//// [react.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +require("./preact"), _jsxdevruntime.Fragment; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx.1.normal.js similarity index 94% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma.1.normal.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx.1.normal.js index a061d0ee193d..14bbf7fff39a 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx.1.normal.js @@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _jsxruntime = require("preact/jsx-runtime"); +var _jsxruntime = require("react/jsx-runtime"); var a = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, { children: [ /*#__PURE__*/ (0, _jsxruntime.jsx)("p", {}), diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx.2.minified.js similarity index 85% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx.2.minified.js index 1132370a5489..ed13d8f007e0 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImportPragma_react-jsx.2.minified.js @@ -1,7 +1,7 @@ //// [preact.tsx] Object.defineProperty(exports, "__esModule", { value: !0 -}), require("preact/jsx-runtime").Fragment; +}), require("react/jsx-runtime").Fragment; //// [react.tsx] Object.defineProperty(exports, "__esModule", { value: !0 diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..ffd4606941ac --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx-dev.1.normal.js @@ -0,0 +1,24 @@ +//// [jsxJsxsCjsTransformCustomImport.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)(_jsxdevruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("p", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformCustomImport.tsx", + lineNumber: 3, + columnNumber: 3 + }, void 0), + "text", + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + className: "foo" + }, void 0, false, { + fileName: "jsxJsxsCjsTransformCustomImport.tsx", + lineNumber: 5, + columnNumber: 3 + }, void 0) + ] +}, void 0, true); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..38abd958cfc5 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx-dev.2.minified.js @@ -0,0 +1,4 @@ +//// [jsxJsxsCjsTransformCustomImport.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}), require("react/jsx-dev-runtime").Fragment; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx.1.normal.js new file mode 100644 index 000000000000..54ea4b8cb917 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx.1.normal.js @@ -0,0 +1,16 @@ +//// [jsxJsxsCjsTransformCustomImport.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxruntime = require("react/jsx-runtime"); +var a = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxruntime.jsx)("p", {}), + "text", + /*#__PURE__*/ (0, _jsxruntime.jsx)("div", { + className: "foo" + }) + ] +}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx.2.minified.js similarity index 70% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx.2.minified.js index 0162aa6a9eaa..d592248caf9c 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformCustomImport_react-jsx.2.minified.js @@ -1,4 +1,4 @@ //// [jsxJsxsCjsTransformCustomImport.tsx] Object.defineProperty(exports, "__esModule", { value: !0 -}), React.Fragment; +}), require("react/jsx-runtime").Fragment; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..59a680b07706 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx-dev.1.normal.js @@ -0,0 +1,59 @@ +//// [preact.tsx] +/// +/* @jsxImportSource preact */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _object_spread = require("@swc/helpers/_/_object_spread"); +var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var _react = require("react"); +var props = { + answer: 42 +}; +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", _object_spread_props._(_object_spread._({}, props), { + children: "text" +}), "foo", false, { + fileName: "preact.tsx", + lineNumber: 4, + columnNumber: 11 +}, void 0); +var b = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props), { + key: "bar", + __source: { + fileName: "preact.tsx", + lineNumber: 5, + columnNumber: 11 + }, + __self: void 0 +}), "text"); +//// [react.tsx] +/// +/* @jsxImportSource react */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _object_spread = require("@swc/helpers/_/_object_spread"); +var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var _react = require("react"); +require("./preact"); +var props2 = { + answer: 42 +}; +var a2 = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", _object_spread_props._(_object_spread._({}, props2), { + children: "text" +}), "foo", false, { + fileName: "react.tsx", + lineNumber: 5, + columnNumber: 12 +}, void 0); +var b2 = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props2), { + key: "bar", + __source: { + fileName: "react.tsx", + lineNumber: 6, + columnNumber: 12 + }, + __self: void 0 +}), "text"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..cc2cb6a2e477 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx-dev.2.minified.js @@ -0,0 +1,40 @@ +//// [preact.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +require("react/jsx-dev-runtime"), require("react"); +var props = { + answer: 42 +}; +_object_spread_props._(_object_spread._({}, props), { + children: "text" +}), _object_spread_props._(_object_spread._({}, props), { + key: "bar", + __source: { + fileName: "preact.tsx", + lineNumber: 5, + columnNumber: 11 + }, + __self: void 0 +}); +//// [react.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +require("react/jsx-dev-runtime"), require("react"), require("./preact"); +var props2 = { + answer: 42 +}; +_object_spread_props._(_object_spread._({}, props2), { + children: "text" +}), _object_spread_props._(_object_spread._({}, props2), { + key: "bar", + __source: { + fileName: "react.tsx", + lineNumber: 6, + columnNumber: 12 + }, + __self: void 0 +}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx.1.normal.js similarity index 86% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma.1.normal.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx.1.normal.js index 999afa429200..f7d7d96e4b90 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx.1.normal.js @@ -6,15 +6,15 @@ Object.defineProperty(exports, "__esModule", { }); var _object_spread = require("@swc/helpers/_/_object_spread"); var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); -var _jsxruntime = require("preact/jsx-runtime"); -var _preact = require("preact"); +var _jsxruntime = require("react/jsx-runtime"); +var _react = require("react"); var props = { answer: 42 }; var a = /*#__PURE__*/ (0, _jsxruntime.jsx)("div", _object_spread_props._(_object_spread._({}, props), { children: "text" }), "foo"); -var b = /*#__PURE__*/ (0, _preact.createElement)("div", _object_spread_props._(_object_spread._({}, props), { +var b = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props), { key: "bar" }), "text"); //// [react.tsx] diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx.2.minified.js similarity index 94% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx.2.minified.js index 7887fda63721..741195065513 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImportPragma_react-jsx.2.minified.js @@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: !0 }); var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); -require("preact/jsx-runtime"), require("preact"); +require("react/jsx-runtime"), require("react"); var props = { answer: 42 }; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..d5694904108c --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx-dev.1.normal.js @@ -0,0 +1,29 @@ +//// [jsxJsxsCjsTransformKeyPropCustomImport.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _object_spread = require("@swc/helpers/_/_object_spread"); +var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var _react = require("react"); +var props = { + answer: 42 +}; +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", _object_spread_props._(_object_spread._({}, props), { + children: "text" +}), "foo", false, { + fileName: "jsxJsxsCjsTransformKeyPropCustomImport.tsx", + lineNumber: 3, + columnNumber: 11 +}, void 0); +var b = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props), { + key: "bar", + __source: { + fileName: "jsxJsxsCjsTransformKeyPropCustomImport.tsx", + lineNumber: 4, + columnNumber: 11 + }, + __self: void 0 +}), "text"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..abc837a1607d --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx-dev.2.minified.js @@ -0,0 +1,20 @@ +//// [jsxJsxsCjsTransformKeyPropCustomImport.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +require("react/jsx-dev-runtime"), require("react"); +var props = { + answer: 42 +}; +_object_spread_props._(_object_spread._({}, props), { + children: "text" +}), _object_spread_props._(_object_spread._({}, props), { + key: "bar", + __source: { + fileName: "jsxJsxsCjsTransformKeyPropCustomImport.tsx", + lineNumber: 4, + columnNumber: 11 + }, + __self: void 0 +}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx.1.normal.js similarity index 53% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport.1.normal.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx.1.normal.js index ed92477f6a90..11334766ab08 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx.1.normal.js @@ -6,12 +6,14 @@ Object.defineProperty(exports, "__esModule", { }); var _object_spread = require("@swc/helpers/_/_object_spread"); var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +var _jsxruntime = require("react/jsx-runtime"); +var _react = require("react"); var props = { answer: 42 }; -var a = /*#__PURE__*/ React.createElement("div", _object_spread._({ - key: "foo" -}, props), "text"); -var b = /*#__PURE__*/ React.createElement("div", _object_spread_props._(_object_spread._({}, props), { +var a = /*#__PURE__*/ (0, _jsxruntime.jsx)("div", _object_spread_props._(_object_spread._({}, props), { + children: "text" +}), "foo"); +var b = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props), { key: "bar" }), "text"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx.2.minified.js similarity index 58% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx.2.minified.js index 106370bd9dde..37bed9def4ef 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyPropCustomImport_react-jsx.2.minified.js @@ -2,11 +2,13 @@ Object.defineProperty(exports, "__esModule", { value: !0 }); -var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"), props = { +var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +require("react/jsx-runtime"), require("react"); +var props = { answer: 42 }; -_object_spread._({ - key: "foo" -}, props), _object_spread_props._(_object_spread._({}, props), { +_object_spread_props._(_object_spread._({}, props), { + children: "text" +}), _object_spread_props._(_object_spread._({}, props), { key: "bar" }); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..0cd499a5226a --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx-dev.1.normal.js @@ -0,0 +1,29 @@ +//// [jsxJsxsCjsTransformKeyProp.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _object_spread = require("@swc/helpers/_/_object_spread"); +var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var _react = require("react"); +var props = { + answer: 42 +}; +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", _object_spread_props._(_object_spread._({}, props), { + children: "text" +}), "foo", false, { + fileName: "jsxJsxsCjsTransformKeyProp.tsx", + lineNumber: 3, + columnNumber: 11 +}, void 0); +var b = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props), { + key: "bar", + __source: { + fileName: "jsxJsxsCjsTransformKeyProp.tsx", + lineNumber: 4, + columnNumber: 11 + }, + __self: void 0 +}), "text"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..341fa13defb2 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx-dev.2.minified.js @@ -0,0 +1,20 @@ +//// [jsxJsxsCjsTransformKeyProp.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +require("react/jsx-dev-runtime"), require("react"); +var props = { + answer: 42 +}; +_object_spread_props._(_object_spread._({}, props), { + children: "text" +}), _object_spread_props._(_object_spread._({}, props), { + key: "bar", + __source: { + fileName: "jsxJsxsCjsTransformKeyProp.tsx", + lineNumber: 4, + columnNumber: 11 + }, + __self: void 0 +}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx.1.normal.js similarity index 52% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp.1.normal.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx.1.normal.js index defbd9dd1cf6..09b9ced5958c 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx.1.normal.js @@ -6,12 +6,14 @@ Object.defineProperty(exports, "__esModule", { }); var _object_spread = require("@swc/helpers/_/_object_spread"); var _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +var _jsxruntime = require("react/jsx-runtime"); +var _react = require("react"); var props = { answer: 42 }; -var a = /*#__PURE__*/ React.createElement("div", _object_spread._({ - key: "foo" -}, props), "text"); -var b = /*#__PURE__*/ React.createElement("div", _object_spread_props._(_object_spread._({}, props), { +var a = /*#__PURE__*/ (0, _jsxruntime.jsx)("div", _object_spread_props._(_object_spread._({}, props), { + children: "text" +}), "foo"); +var b = /*#__PURE__*/ (0, _react.createElement)("div", _object_spread_props._(_object_spread._({}, props), { key: "bar" }), "text"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx.2.minified.js similarity index 57% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx.2.minified.js index da0c8e7df06f..59157c6a7e54 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformKeyProp_react-jsx.2.minified.js @@ -2,11 +2,13 @@ Object.defineProperty(exports, "__esModule", { value: !0 }); -var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"), props = { +var _object_spread = require("@swc/helpers/_/_object_spread"), _object_spread_props = require("@swc/helpers/_/_object_spread_props"); +require("react/jsx-runtime"), require("react"); +var props = { answer: 42 }; -_object_spread._({ - key: "foo" -}, props), _object_spread_props._(_object_spread._({}, props), { +_object_spread_props._(_object_spread._({}, props), { + children: "text" +}), _object_spread_props._(_object_spread._({}, props), { key: "bar" }); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild.1.normal.js deleted file mode 100644 index a4d9d693412f..000000000000 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild.1.normal.js +++ /dev/null @@ -1,16 +0,0 @@ -//// [jsxJsxsCjsTransformNestedSelfClosingChild.tsx] -/// -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -console.log(/*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("div", null))); -console.log(/*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("div", null), /*#__PURE__*/ React.createElement("div", null))); -console.log(/*#__PURE__*/ React.createElement("div", null, [ - 1, - 2 -].map(function(i) { - return /*#__PURE__*/ React.createElement("div", { - key: i - }, i); -}))); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild.2.minified.js deleted file mode 100644 index da23879d111f..000000000000 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild.2.minified.js +++ /dev/null @@ -1,11 +0,0 @@ -//// [jsxJsxsCjsTransformNestedSelfClosingChild.tsx] -Object.defineProperty(exports, "__esModule", { - value: !0 -}), console.log(React.createElement("div", null, React.createElement("div", null))), console.log(React.createElement("div", null, React.createElement("div", null), React.createElement("div", null))), console.log(React.createElement("div", null, [ - 1, - 2 -].map(function(i) { - return React.createElement("div", { - key: i - }, i); -}))); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..2ef2352c383f --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx-dev.1.normal.js @@ -0,0 +1,55 @@ +//// [jsxJsxsCjsTransformNestedSelfClosingChild.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var _this = void 0; +console.log(/*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + children: /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 6, + columnNumber: 5 + }, void 0) +}, void 0, false, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 5, + columnNumber: 3 +}, void 0)); +console.log(/*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + children: [ + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 12, + columnNumber: 5 + }, void 0), + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 13, + columnNumber: 5 + }, void 0) + ] +}, void 0, true, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 11, + columnNumber: 3 +}, void 0)); +console.log(/*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + children: [ + 1, + 2 + ].map(function(i) { + return /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", { + children: i + }, i, false, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 19, + columnNumber: 22 + }, _this); + }) +}, void 0, false, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 18, + columnNumber: 3 +}, void 0)); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..0339dbec9903 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx-dev.2.minified.js @@ -0,0 +1,50 @@ +//// [jsxJsxsCjsTransformNestedSelfClosingChild.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"), _this = void 0; +console.log((0, _jsxdevruntime.jsxDEV)("div", { + children: (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, !1, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 6, + columnNumber: 5 + }, void 0) +}, void 0, !1, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 5, + columnNumber: 3 +}, void 0)), console.log((0, _jsxdevruntime.jsxDEV)("div", { + children: [ + (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, !1, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 12, + columnNumber: 5 + }, void 0), + (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, !1, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 13, + columnNumber: 5 + }, void 0) + ] +}, void 0, !0, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 11, + columnNumber: 3 +}, void 0)), console.log((0, _jsxdevruntime.jsxDEV)("div", { + children: [ + 1, + 2 + ].map(function(i) { + return (0, _jsxdevruntime.jsxDEV)("div", { + children: i + }, i, !1, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 19, + columnNumber: 22 + }, _this); + }) +}, void 0, !1, { + fileName: "jsxJsxsCjsTransformNestedSelfClosingChild.tsx", + lineNumber: 18, + columnNumber: 3 +}, void 0)); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx.1.normal.js new file mode 100644 index 000000000000..4144d7397872 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx.1.normal.js @@ -0,0 +1,26 @@ +//// [jsxJsxsCjsTransformNestedSelfClosingChild.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxruntime = require("react/jsx-runtime"); +console.log(/*#__PURE__*/ (0, _jsxruntime.jsx)("div", { + children: /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {}) +})); +console.log(/*#__PURE__*/ (0, _jsxruntime.jsxs)("div", { + children: [ + /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {}), + /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {}) + ] +})); +console.log(/*#__PURE__*/ (0, _jsxruntime.jsx)("div", { + children: [ + 1, + 2 + ].map(function(i) { + return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", { + children: i + }, i); + }) +})); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx.2.minified.js new file mode 100644 index 000000000000..1368ed3f401e --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformNestedSelfClosingChild_react-jsx.2.minified.js @@ -0,0 +1,22 @@ +//// [jsxJsxsCjsTransformNestedSelfClosingChild.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}); +var _jsxruntime = require("react/jsx-runtime"); +console.log((0, _jsxruntime.jsx)("div", { + children: (0, _jsxruntime.jsx)("div", {}) +})), console.log((0, _jsxruntime.jsxs)("div", { + children: [ + (0, _jsxruntime.jsx)("div", {}), + (0, _jsxruntime.jsx)("div", {}) + ] +})), console.log((0, _jsxruntime.jsx)("div", { + children: [ + 1, + 2 + ].map(function(i) { + return (0, _jsxruntime.jsx)("div", { + children: i + }, i); + }) +})); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment.1.normal.js deleted file mode 100644 index 30ad05fc9741..000000000000 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment.1.normal.js +++ /dev/null @@ -1,7 +0,0 @@ -//// [jsxJsxsCjsTransformSubstitutesNamesFragment.tsx] -/// -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -var a = /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("p", null), "text", /*#__PURE__*/ React.createElement("div", null)); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..215aa84aab8d --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx-dev.1.normal.js @@ -0,0 +1,22 @@ +//// [jsxJsxsCjsTransformSubstitutesNamesFragment.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)(_jsxdevruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("p", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformSubstitutesNamesFragment.tsx", + lineNumber: 3, + columnNumber: 3 + }, void 0), + "text", + /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformSubstitutesNamesFragment.tsx", + lineNumber: 5, + columnNumber: 3 + }, void 0) + ] +}, void 0, true); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..9bf6426f2a3b --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx-dev.2.minified.js @@ -0,0 +1,4 @@ +//// [jsxJsxsCjsTransformSubstitutesNamesFragment.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}), require("react/jsx-dev-runtime").Fragment; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx.1.normal.js new file mode 100644 index 000000000000..27bbf7130473 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx.1.normal.js @@ -0,0 +1,14 @@ +//// [jsxJsxsCjsTransformSubstitutesNamesFragment.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxruntime = require("react/jsx-runtime"); +var a = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxruntime.jsx)("p", {}), + "text", + /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {}) + ] +}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx.2.minified.js similarity index 72% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx.2.minified.js index 5027af0a3a7c..79517238c446 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNamesFragment_react-jsx.2.minified.js @@ -1,4 +1,4 @@ //// [jsxJsxsCjsTransformSubstitutesNamesFragment.tsx] Object.defineProperty(exports, "__esModule", { value: !0 -}), React.Fragment; +}), require("react/jsx-runtime").Fragment; diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..c3b06d18b72d --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx-dev.1.normal.js @@ -0,0 +1,12 @@ +//// [jsxJsxsCjsTransformSubstitutesNames.tsx] +/// +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _jsxdevruntime = require("react/jsx-dev-runtime"); +var a = /*#__PURE__*/ (0, _jsxdevruntime.jsxDEV)("div", {}, void 0, false, { + fileName: "jsxJsxsCjsTransformSubstitutesNames.tsx", + lineNumber: 2, + columnNumber: 11 +}, void 0); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..caf43639e7b7 --- /dev/null +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx-dev.2.minified.js @@ -0,0 +1,4 @@ +//// [jsxJsxsCjsTransformSubstitutesNames.tsx] +Object.defineProperty(exports, "__esModule", { + value: !0 +}), require("react/jsx-dev-runtime"); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames.1.normal.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx.1.normal.js similarity index 62% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames.1.normal.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx.1.normal.js index 985cbe32c5f8..ab003ae227e5 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx.1.normal.js @@ -4,4 +4,5 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var a = /*#__PURE__*/ React.createElement("div", null); +var _jsxruntime = require("react/jsx-runtime"); +var a = /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {}); diff --git a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames.2.minified.js b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx.2.minified.js similarity index 76% rename from crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames.2.minified.js rename to crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx.2.minified.js index dc38d49c0f9f..cee7673fd91f 100644 --- a/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxJsxsCjsTransformSubstitutesNames_react-jsx.2.minified.js @@ -1,4 +1,4 @@ //// [jsxJsxsCjsTransformSubstitutesNames.tsx] Object.defineProperty(exports, "__esModule", { value: !0 -}); +}), require("react/jsx-runtime"); diff --git a/crates/swc/tests/tsc-references/jsxReactTestSuite.1.normal.js b/crates/swc/tests/tsc-references/jsxReactTestSuite.1.normal.js index 914a84eee937..d487a787be12 100644 --- a/crates/swc/tests/tsc-references/jsxReactTestSuite.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxReactTestSuite.1.normal.js @@ -1,64 +1,52 @@ //// [jsxReactTestSuite.tsx] -import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; -/*#__PURE__*/ React.createElement("div", null, "text"); -/*#__PURE__*/ React.createElement("div", null, this.props.children); -/*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("br", null)), /*#__PURE__*/ React.createElement(Component, null, foo, /*#__PURE__*/ React.createElement("br", null), bar), /*#__PURE__*/ React.createElement("br", null)); -/*#__PURE__*/ React.createElement(Composite, null, this.props.children); -/*#__PURE__*/ React.createElement(Composite, null, /*#__PURE__*/ React.createElement(Composite2, null)); -var x = /*#__PURE__*/ React.createElement("div", { - attr1: "foo" + "bar", - attr2: "foo" + "bar" + "baz" + "bug", - attr3: "foo" + "bar" + "baz" + "bug", - attr4: "baz" -}); -/*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("span", null), /*#__PURE__*/ React.createElement("br", null)); -/*#__PURE__*/ React.createElement("div", { - /* a multi-line - comment */ attr1: "foo" -}, /*#__PURE__*/ React.createElement("span" // a double-slash comment -, { - attr2: "bar" -})); -/*#__PURE__*/ React.createElement("div", null, "\xa0"); -/*#__PURE__*/ React.createElement("div", null, "\xa0 "); -/*#__PURE__*/ React.createElement("hasOwnProperty", null, "testing"); -/*#__PURE__*/ React.createElement(Component, { - constructor: "foo" -}); -/*#__PURE__*/ React.createElement(Namespace.Component, null); -/*#__PURE__*/ React.createElement(Namespace.DeepNamespace.Component, null); -/*#__PURE__*/ React.createElement(Component, _object_spread_props(_object_spread({}, x), { - y: 2, - z: true -})); -/*#__PURE__*/ React.createElement(Component, _object_spread_props(_object_spread({}, this.props), { - sound: "moo" -})); -/*#__PURE__*/ React.createElement("font-face", null); -/*#__PURE__*/ React.createElement(Component, { - x: y -}); -/*#__PURE__*/ React.createElement("x-component", null); -/*#__PURE__*/ React.createElement(Component, x); -/*#__PURE__*/ React.createElement(Component, _object_spread_props(_object_spread({}, x), { +
text
; +
+ {this.props.children} +
; +
+

+ {foo}
{bar}
+
+
; + + {this.props.children} +; + + +; +var x =
+
; +
+ { /* A comment at the beginning */ } + { /* A second comment at the beginning */ } + + { /* A nested comment */ } + + { /* A sandwiched comment */ } +
+ { /* A comment at the end */ } + { /* A second comment at the end */ } +
; +
+ +
; +
 
; +
 
; +testing; +; +; +; +; +; +; +; +; +; +; +; +; +; +Text; diff --git a/crates/swc/tests/tsc-references/jsxReactTestSuite.2.minified.js b/crates/swc/tests/tsc-references/jsxReactTestSuite.2.minified.js index 881f3957d41a..f58c7acbc59e 100644 --- a/crates/swc/tests/tsc-references/jsxReactTestSuite.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxReactTestSuite.2.minified.js @@ -1,32 +1,29 @@ //// [jsxReactTestSuite.tsx] -import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; -this.props.children, Component, foo, bar, Composite, this.props.children, Composite, Composite2; -var x = React.createElement("div", { - attr1: "foobar", - attr2: "foobarbazbug", - attr3: "foobarbazbug", - attr4: "baz" -}); -Component, Namespace.Component, Namespace.DeepNamespace.Component, Component, _object_spread_props(_object_spread({}, x), { - y: 2, - z: !0 -}), Component, _object_spread_props(_object_spread({}, this.props), { - sound: "moo" -}), Component, y, Component, Component, _object_spread_props(_object_spread({}, x), { +
text
,
+ {this.props.children} +
,
+

+ {foo}
{bar}
+
+
, + {this.props.children} +, + +; +var x =
+
; +
+ {} + {} + + {} + + {} +
+ {} + {} +
,
+ +
,
 
,
 
, testing, , , , , , , , , , , , , , Text; diff --git a/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.1.normal.js b/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.1.normal.js index 7244306022b7..88ca341873f8 100644 --- a/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.1.normal.js +++ b/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.1.normal.js @@ -1,10 +1,21 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface Props { -//! 5 | a: number; -//! `---- +var props = { + a: 1, + b: 1 +}; +var Foo = function(props) { + return
{props.a}
; +}; +// ok +var a1 = ; +var a2 = ; +// error +var b1 = ; +var b2 = ; +var b3 = ; +var b4 = ; diff --git a/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.2.minified.js b/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.2.minified.js index 7244306022b7..13d3612484fe 100644 --- a/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.2.minified.js +++ b/crates/swc/tests/tsc-references/jsxSpreadOverwritesAttributeStrict.2.minified.js @@ -1,10 +1,13 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface Props { -//! 5 | a: number; -//! `---- +var props = { + a: 1, + b: 1 +}, Foo = function(props) { + return
{props.a}
; +}; +, , , , , ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeErrors.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeErrors.1.normal.js index d3c35274c5f1..0e843c31138a 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeErrors.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeErrors.1.normal.js @@ -1,19 +1,12 @@ //// [tsxAttributeErrors.tsx] // Error, number is not assignable to string -/*#__PURE__*/ React.createElement("div", { - text: 42 -}); +
; // Error, string is not assignable to number -/*#__PURE__*/ React.createElement("div", { - width: 'foo' -}); +
; // Error, number is not assignable to string var attribs = { text: 100 }; -/*#__PURE__*/ React.createElement("div", attribs); +
; // No errors here -/*#__PURE__*/ React.createElement("span", { - foo: "bar", - bar: 'foo' -}); +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeErrors.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeErrors.2.minified.js index b18e9cd20562..3295ce3f18d3 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeErrors.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeErrors.2.minified.js @@ -1 +1,4 @@ //// [tsxAttributeErrors.tsx] +
,
,
, ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution1.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution1.1.normal.js index b91e85710675..c145961d4aef 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution1.1.normal.js @@ -1,39 +1,17 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("test1", { - x: 0 -}); // OK -/*#__PURE__*/ React.createElement("test1", null); // OK -/*#__PURE__*/ React.createElement("test1", { - "data-x": true -}); // OK -/*#__PURE__*/ React.createElement("test2", { - reqd: "true" -}); // OK -/*#__PURE__*/ React.createElement("test2", { - reqd: 'true' -}); // OK +; // OK +; // OK +; // OK +; // OK +; // OK // Errors -/*#__PURE__*/ React.createElement("test1", { - x: '0' -}); // Error, '0' is not number -/*#__PURE__*/ React.createElement("test1", { - y: 0 -}); // Error, no property "y" -/*#__PURE__*/ React.createElement("test1", { - y: "foo" -}); // Error, no property "y" -/*#__PURE__*/ React.createElement("test1", { - x: "32" -}); // Error, "32" is not number -/*#__PURE__*/ React.createElement("test1", { - var: "10" -}); // Error, no 'var' property -/*#__PURE__*/ React.createElement("test2", null); // Error, missing reqd -/*#__PURE__*/ React.createElement("test2", { - reqd: 10 -}); // Error, reqd is not string +; // Error, '0' is not number +; // Error, no property "y" +; // Error, no property "y" +; // Error, "32" is not number +; // Error, no 'var' property +; // Error, missing reqd +; // Error, reqd is not string // Should be OK -/*#__PURE__*/ React.createElement("var", { - var: "var" -}); +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution1.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution1.2.minified.js index a68a69cc28c4..66a2e8358689 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution1.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +, , , , , , , , , , , , ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution10.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution10.1.normal.js index 8408687a2501..9809c9cc1827 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution10.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution10.1.normal.js @@ -36,15 +36,9 @@ define([ return MyComponent; }(); // Should be an error - /*#__PURE__*/ React.createElement(MyComponent, { - bar: "world" - }); + ; // Should be OK - /*#__PURE__*/ React.createElement(MyComponent, { - bar: true - }); + ; // Should be ok - /*#__PURE__*/ React.createElement(MyComponent, { - "data-bar": "hello" - }); + ; }); diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution10.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution10.2.minified.js index 6131d55d44c6..e86f46416342 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution10.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution10.2.minified.js @@ -26,4 +26,5 @@ define([ } return MyComponent.prototype.render = function() {}, MyComponent; }(); + , , ; }); diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution11.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution11.1.normal.js index d01ac98269e1..09858cbf770a 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution11.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution11.1.normal.js @@ -30,7 +30,5 @@ define([ return MyComponent; }(); // Should be an OK - var x = /*#__PURE__*/ React.createElement(MyComponent, { - bar: "world" - }); + var x = ; }); diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution11.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution11.2.minified.js index 7644e4a6489c..60a715456eb5 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution11.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution11.2.minified.js @@ -15,4 +15,11 @@ define([ Object.defineProperty(exports, "__esModule", { value: !0 }); + var MyComponent = /*#__PURE__*/ function() { + function MyComponent() { + _class_call_check._(this, MyComponent); + } + return MyComponent.prototype.render = function() {}, MyComponent; + }(); + ; }); diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution12.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution12.1.normal.js index bb2d8d57c1a0..35ac3e8a89d1 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution12.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution12.1.normal.js @@ -3,6 +3,6 @@ //// [file.tsx] // Errors correctly var T = TestMod.Test; -var t1 = /*#__PURE__*/ React.createElement(T, null); +var t1 = ; // Should error -var t2 = /*#__PURE__*/ React.createElement(TestMod.Test, null); +var t2 = ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution12.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution12.2.minified.js index 78ba9285b56f..fa6726a4c55f 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution12.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution12.2.minified.js @@ -1,4 +1,5 @@ //// [tsxAttributeResolution12.tsx] //// [react.d.ts] //// [file.tsx] -TestMod.Test, TestMod.Test; +var T = TestMod.Test; +, ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution13.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution13.1.normal.js index 28c0d1f7376f..5df02e6bba52 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution13.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution13.1.normal.js @@ -1,4 +1,4 @@ //// [tsxAttributeResolution13.tsx] //// [test.tsx] function Test() {} -/*#__PURE__*/ React.createElement(Test, null); +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution13.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution13.2.minified.js index 6c31e79428f9..5df02e6bba52 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution13.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution13.2.minified.js @@ -1,2 +1,4 @@ //// [tsxAttributeResolution13.tsx] //// [test.tsx] +function Test() {} +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution14.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution14.1.normal.js index 1e64924bab51..08a1af4a7282 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution14.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution14.1.normal.js @@ -16,17 +16,13 @@ define([ ], function(require) { "use strict"; function VerticalNavMenuItem(prop) { - return /*#__PURE__*/ React.createElement("div", null, "props.primaryText"); + return
props.primaryText
; } function VerticalNav() { - return /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(VerticalNavMenuItem, { - primaryText: 2 - }), " // error", /*#__PURE__*/ React.createElement(VerticalNavMenuItem, { - justRandomProp: 2, - primaryText: "hello" - }), " // ok", /*#__PURE__*/ React.createElement(VerticalNavMenuItem, { - justRandomProp1: true, - primaryText: "hello" - }), " // error"); + return
+ // error + // ok + // error +
; } }); diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution2.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution2.1.normal.js index 158b2b4d6630..134d16f1f720 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution2.1.normal.js @@ -1,18 +1,12 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("test1", { - c1: function(x) { - return x.length; - } -}); // OK -/*#__PURE__*/ React.createElement("test1", { - "data-c1": function(x) { - return x.leng; - } -}); // OK +; // OK +; // OK // Errors -/*#__PURE__*/ React.createElement("test1", { - c1: function(x) { - return x.leng; - } -}); // Error, no leng on 'string' +; // Error, no leng on 'string' diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution2.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution2.2.minified.js index a68a69cc28c4..3567c44ea1a2 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution2.2.minified.js @@ -1 +1,8 @@ //// [file.tsx] +, , ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution3.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution3.1.normal.js index e68b2213bd1a..b42642b7ea7e 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution3.1.normal.js @@ -1,48 +1,40 @@ //// [file.tsx] -import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; // OK var obj1 = { x: 'foo' }; -/*#__PURE__*/ React.createElement("test1", obj1); +; // Error, x is not string var obj2 = { x: 32 }; -/*#__PURE__*/ React.createElement("test1", obj2); +; // Error, x is missing var obj3 = { y: 32 }; -/*#__PURE__*/ React.createElement("test1", obj3); +; // OK var obj4 = { x: 32, y: 32 }; -/*#__PURE__*/ React.createElement("test1", _object_spread_props(_object_spread({}, obj4), { - x: "ok" -})); +; // Error var obj5 = { x: 32, y: 32 }; -/*#__PURE__*/ React.createElement("test1", _object_spread({ - x: "ok" -}, obj5)); +; // Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; -/*#__PURE__*/ React.createElement("test1", obj6); +; // OK (spread override) var obj7 = { x: 'foo' }; -/*#__PURE__*/ React.createElement("test1", _object_spread({ - x: 32 -}, obj7)); +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution3.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution3.2.minified.js index ad6cee1d359e..5f608dff6c57 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution3.2.minified.js @@ -1,18 +1,20 @@ //// [file.tsx] -import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; -_object_spread_props(_object_spread({}, { +, , , , , , ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution4.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution4.1.normal.js index a3a82cf5f706..85577f1b7693 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution4.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution4.1.normal.js @@ -1,13 +1,13 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("test1", { +; // Error, no member 'len' on 'string' -/*#__PURE__*/ React.createElement("test1", { +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution4.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution4.2.minified.js index a68a69cc28c4..a6d4757af427 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution4.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution4.2.minified.js @@ -1 +1,10 @@ //// [file.tsx] +, ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution5.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution5.1.normal.js index ddf66d369079..bf81a3f6cc23 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution5.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution5.1.normal.js @@ -1,12 +1,12 @@ //// [file.tsx] function make1(obj) { - return /*#__PURE__*/ React.createElement("test1", obj); // OK + return ; // OK } function make2(obj) { - return /*#__PURE__*/ React.createElement("test1", obj); // Error (x is number, not string) + return ; // Error (x is number, not string) } function make3(obj) { - return /*#__PURE__*/ React.createElement("test1", obj); // Error, missing x + return ; // Error, missing x } -/*#__PURE__*/ React.createElement("test1", {}); // Error, missing x -/*#__PURE__*/ React.createElement("test2", {}); // Error, missing toString +; // Error, missing x +; // Error, missing toString diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution5.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution5.2.minified.js index a68a69cc28c4..19514ed7cfe3 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution5.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution5.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +, ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution6.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution6.1.normal.js index 16a9dbd6cdb8..cee4f4aaa46a 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution6.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution6.1.normal.js @@ -1,19 +1,9 @@ //// [file.tsx] // Error -/*#__PURE__*/ React.createElement("test1", { - s: true -}); -/*#__PURE__*/ React.createElement("test1", { - n: "true" -}); -/*#__PURE__*/ React.createElement("test2", null); +; +; +; // OK -/*#__PURE__*/ React.createElement("test1", { - n: true -}); -/*#__PURE__*/ React.createElement("test1", { - n: false -}); -/*#__PURE__*/ React.createElement("test2", { - n: true -}); +; +; +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution6.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution6.2.minified.js index a68a69cc28c4..9f8f5fa527ac 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution6.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution6.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +, , , , , ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution7.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution7.1.normal.js index ea33ebd1ff30..19468f6ae601 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution7.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution7.1.normal.js @@ -1,15 +1,7 @@ //// [file.tsx] // Error -/*#__PURE__*/ React.createElement("test1", { - "data-foo": 32 -}); +; // OK -/*#__PURE__*/ React.createElement("test1", { - "data-foo": '32' -}); -/*#__PURE__*/ React.createElement("test1", { - "data-bar": '32' -}); -/*#__PURE__*/ React.createElement("test1", { - "data-bar": 32 -}); +; +; +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution7.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution7.2.minified.js index a68a69cc28c4..b649468b1398 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution7.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution7.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +, , , ; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution8.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution8.1.normal.js index 755ad7044c34..56d8cb5bb998 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution8.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution8.1.normal.js @@ -1,4 +1,4 @@ //// [file.tsx] var x; // Should be OK -/*#__PURE__*/ React.createElement("test1", x); +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution8.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution8.2.minified.js index a68a69cc28c4..964dbe70db75 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution8.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution8.2.minified.js @@ -1 +1,3 @@ //// [file.tsx] +var x; +; diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution9.1.normal.js b/crates/swc/tests/tsc-references/tsxAttributeResolution9.1.normal.js index 061283ec85fa..e5fdd963d93b 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution9.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution9.1.normal.js @@ -35,10 +35,6 @@ define([ _proto.render = function render() {}; return MyComponent; }(); - /*#__PURE__*/ React.createElement(MyComponent, { - foo: "bar" - }); // ok - /*#__PURE__*/ React.createElement(MyComponent, { - foo: 0 - }); // should be an error + ; // ok + ; // should be an error }); diff --git a/crates/swc/tests/tsc-references/tsxAttributeResolution9.2.minified.js b/crates/swc/tests/tsc-references/tsxAttributeResolution9.2.minified.js index 7110a394cfad..e2d99f1f3533 100644 --- a/crates/swc/tests/tsc-references/tsxAttributeResolution9.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxAttributeResolution9.2.minified.js @@ -26,4 +26,5 @@ define([ } return MyComponent.prototype.render = function() {}, MyComponent; }(); + , ; }); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName1.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName1.1.normal.js index a27c9d7779c4..026c7f0d2bbc 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName1.1.normal.js @@ -1,3 +1,3 @@ //// [tsxDynamicTagName1.tsx] var CustomTag = "h1"; -/*#__PURE__*/ React.createElement(CustomTag, null, " Hello World "); // No error + Hello World ; // No error diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName1.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName1.2.minified.js index bef34fc966ad..5e3d317aacd8 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName1.2.minified.js @@ -1 +1,2 @@ //// [tsxDynamicTagName1.tsx] + Hello World ; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName2.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName2.1.normal.js index 9963f5d89785..01c1df15fa0d 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName2.1.normal.js @@ -1,3 +1,3 @@ //// [tsxDynamicTagName2.tsx] -var customTag = "h1"; -/*#__PURE__*/ React.createElement("customTag", null, " Hello World "); // This should be an error. The lower-case is look up as an intrinsic element name +var customTag1 = "h1"; + Hello World ; // This should be an error. The lower-case is look up as an intrinsic element name diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName2.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName2.2.minified.js index 28f66fa79006..4b48ab3d12eb 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName2.2.minified.js @@ -1 +1,2 @@ //// [tsxDynamicTagName2.tsx] + Hello World ; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName3.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName3.1.normal.js index 743b60397e8f..daff34da6bae 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName3.1.normal.js @@ -1,3 +1,3 @@ //// [tsxDynamicTagName3.tsx] var CustomTag = "h1"; -/*#__PURE__*/ React.createElement(CustomTag, null, " Hello World "); // This should be an error. we will try look up string literal type in JSX.IntrinsicElements + Hello World ; // This should be an error. we will try look up string literal type in JSX.IntrinsicElements diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName3.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName3.2.minified.js index f014a2096fa6..34fdae7d25ce 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName3.2.minified.js @@ -1 +1,2 @@ //// [tsxDynamicTagName3.tsx] + Hello World ; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName4.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName4.1.normal.js index 225fd8556f29..74589533739c 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName4.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName4.1.normal.js @@ -1,3 +1,3 @@ //// [tsxDynamicTagName4.tsx] var CustomTag = "h1"; -/*#__PURE__*/ React.createElement(CustomTag, null, " Hello World "); + Hello World ; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName4.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName4.2.minified.js index 69edcf5a8408..6b8f5a114390 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName4.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName4.2.minified.js @@ -1 +1,2 @@ //// [tsxDynamicTagName4.tsx] + Hello World ; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName5.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName5.1.normal.js index 1bb6989f1530..4607b624f42a 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName5.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName5.1.normal.js @@ -16,7 +16,7 @@ export var Text = /*#__PURE__*/ function(_React_Component) { } var _proto = Text.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement(this._tagName, null); + return ; }; return Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName5.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName5.2.minified.js index 67f87e880934..00d6ada2f062 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName5.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName5.2.minified.js @@ -11,6 +11,6 @@ export var Text = /*#__PURE__*/ function(_React_Component) { return _class_call_check(this, Text), _this = _call_super(this, Text, arguments), _this._tagName = 'div', _this; } return _inherits(Text, _React_Component), Text.prototype.render = function() { - return React.createElement(this._tagName, null); + return ; }, Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName6.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName6.1.normal.js index 3b8ca1dced27..611a944b06cb 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName6.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName6.1.normal.js @@ -2,5 +2,5 @@ var t = { tag: 'h1' }; -var foo = /*#__PURE__*/ React.createElement(t.tag, null) // No error +var foo = // No error ; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName6.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName6.2.minified.js index dc366d39de84..7a0ba9ef0cc9 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName6.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName6.2.minified.js @@ -1 +1,2 @@ //// [tsxDynamicTagName6.tsx] +; diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName7.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName7.1.normal.js index 69d378f85abd..582a554eb800 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName7.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName7.1.normal.js @@ -16,7 +16,7 @@ export var Text = /*#__PURE__*/ function(_React_Component) { } var _proto = Text.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement(this, null); + return ; }; return Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName7.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName7.2.minified.js index 8f6c6cca0b6c..0c3c06c2b2fa 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName7.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName7.2.minified.js @@ -11,6 +11,6 @@ export var Text = /*#__PURE__*/ function(_React_Component) { return _class_call_check(this, Text), _this = _call_super(this, Text, arguments), _this._tagName = 'div', _this; } return _inherits(Text, _React_Component), Text.prototype.render = function() { - return React.createElement(this, null); + return ; }, Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName8.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName8.1.normal.js index 89c25c1b467d..a56609c569b8 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName8.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName8.1.normal.js @@ -16,7 +16,7 @@ export var Text = /*#__PURE__*/ function(_React_Component) { } var _proto = Text.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement(this._tagName, null, " Hello world "); + return Hello world ; }; return Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName8.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName8.2.minified.js index c1f04613d627..a743f8b44f20 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName8.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName8.2.minified.js @@ -11,6 +11,6 @@ export var Text = /*#__PURE__*/ function(_React_Component) { return _class_call_check(this, Text), _this = _call_super(this, Text, arguments), _this._tagName = 'div', _this; } return _inherits(Text, _React_Component), Text.prototype.render = function() { - return React.createElement(this._tagName, null, " Hello world "); + return Hello world ; }, Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName9.1.normal.js b/crates/swc/tests/tsc-references/tsxDynamicTagName9.1.normal.js index d93dfa686fbf..b723f258c684 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName9.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName9.1.normal.js @@ -16,7 +16,7 @@ export var Text = /*#__PURE__*/ function(_React_Component) { } var _proto = Text.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement(this._tagName, null, " Hello world "); + return Hello world ; }; return Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxDynamicTagName9.2.minified.js b/crates/swc/tests/tsc-references/tsxDynamicTagName9.2.minified.js index 28e5be9e773f..a6e6c37ecea8 100644 --- a/crates/swc/tests/tsc-references/tsxDynamicTagName9.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxDynamicTagName9.2.minified.js @@ -11,6 +11,6 @@ export var Text = /*#__PURE__*/ function(_React_Component) { return _class_call_check(this, Text), _this = _call_super(this, Text, arguments), _this._tagName = 'div', _this; } return _inherits(Text, _React_Component), Text.prototype.render = function() { - return React.createElement(this._tagName, null, " Hello world "); + return Hello world ; }, Text; }(React.Component); diff --git a/crates/swc/tests/tsc-references/tsxElementResolution.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution.1.normal.js index bc9d5ab62d08..55cf924883a6 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution.1.normal.js @@ -1,8 +1,8 @@ //// [tsxElementResolution.tsx] import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; -var foundFirst = function foundFirst() { +var foundFirst1 = function foundFirst1() { "use strict"; - _class_call_check(this, foundFirst); + _class_call_check(this, foundFirst1); }; var Other = function Other() { "use strict"; @@ -16,13 +16,11 @@ var Other = function Other() { Dotted.Name = Name; })(Dotted || (Dotted = {})); // Should find the intrinsic element, not the class element -var a = /*#__PURE__*/ React.createElement("foundFirst", { - x: "hello" -}); -var b = /*#__PURE__*/ React.createElement("string_named", null); +var a = ; +var b = ; // TODO: This should not be a parse error (should // parse a property name here, not identifier) // var c = ; -var d = /*#__PURE__*/ React.createElement(Other, null); -var e = /*#__PURE__*/ React.createElement(Dotted.Name, null); +var d = ; +var e = ; var Dotted; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution.2.minified.js index 3f6a50ffb39d..ac79878813c2 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution.2.minified.js @@ -1,6 +1,8 @@ //// [tsxElementResolution.tsx] -var Dotted; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; +var Dotted, Other = function Other() { + _class_call_check(this, Other); +}; (Dotted || (Dotted = {})).Name = function Name() { _class_call_check(this, Name); -}, Dotted.Name; +}, , , , ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution1.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution1.1.normal.js index b75ebd84f56f..34bde237623a 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution1.1.normal.js @@ -1,5 +1,5 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("div", null); +
; // Fail -/*#__PURE__*/ React.createElement("span", null); +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution1.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution1.2.minified.js index a68a69cc28c4..e18a0efb54fb 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution1.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
, ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution10.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution10.1.normal.js index 59073fddfbde..18d6011c9e84 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution10.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution10.1.normal.js @@ -1,10 +1,5 @@ //// [file.tsx] var Obj1; -/*#__PURE__*/ React.createElement(Obj1, { - x: 10 -}); // Error, no render member +; // Error, no render member var Obj2; -/*#__PURE__*/ React.createElement(Obj2, { - x: 32, - render: 100 -}); // OK +; // OK diff --git a/crates/swc/tests/tsc-references/tsxElementResolution10.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution10.2.minified.js index a68a69cc28c4..5e1464b1cfa4 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution10.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution10.2.minified.js @@ -1 +1,3 @@ //// [file.tsx] +var Obj1, Obj2; +, ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution11.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution11.1.normal.js index 892b8b6969a5..7a2db3a3c15f 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution11.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution11.1.normal.js @@ -1,13 +1,7 @@ //// [file.tsx] var Obj1; -/*#__PURE__*/ React.createElement(Obj1, { - x: 10 -}); // OK +; // OK var Obj2; -/*#__PURE__*/ React.createElement(Obj2, { - x: 10 -}); // Error +; // Error var Obj3; -/*#__PURE__*/ React.createElement(Obj3, { - x: 10 -}); // OK +; // OK diff --git a/crates/swc/tests/tsc-references/tsxElementResolution11.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution11.2.minified.js index a68a69cc28c4..f5f65d464cb5 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution11.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution11.2.minified.js @@ -1 +1,3 @@ //// [file.tsx] +var Obj1, Obj2, Obj3; +, , ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution12.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution12.1.normal.js index e8b012bc6a71..0ee5259af051 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution12.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution12.1.normal.js @@ -1,23 +1,13 @@ //// [file.tsx] var Obj1; -/*#__PURE__*/ React.createElement(Obj1, { - x: 10 -}); // OK +; // OK var Obj2; -/*#__PURE__*/ React.createElement(Obj2, { - x: 10 -}); // OK +; // OK var Obj3; -/*#__PURE__*/ React.createElement(Obj3, { - x: 10 -}); // Error +; // Error var attributes; -/*#__PURE__*/ React.createElement(Obj3, attributes); // Error -/*#__PURE__*/ React.createElement(Obj3, {}); // OK +; // Error +; // OK var Obj4; -/*#__PURE__*/ React.createElement(Obj4, { - x: 10 -}); // OK -/*#__PURE__*/ React.createElement(Obj4, { - x: '10' -}); // Error +; // OK +; // Error diff --git a/crates/swc/tests/tsc-references/tsxElementResolution12.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution12.2.minified.js index a68a69cc28c4..91fffa5f3ffd 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution12.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution12.2.minified.js @@ -1 +1,3 @@ //// [file.tsx] +var Obj1, Obj2, Obj3, attributes, Obj4; +, , , , , , ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution13.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution13.1.normal.js index baa012353b4f..b88600a74c99 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution13.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution13.1.normal.js @@ -1,5 +1,3 @@ //// [file.tsx] -var obj1; -/*#__PURE__*/ React.createElement("obj1", { - x: 10 -}); // Error +var obj11; +; // Error diff --git a/crates/swc/tests/tsc-references/tsxElementResolution13.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution13.2.minified.js index a68a69cc28c4..ef9ad71bfdd8 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution13.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution13.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution14.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution14.1.normal.js index 6d717f5475df..df5c1d056809 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution14.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution14.1.normal.js @@ -1,5 +1,3 @@ //// [file.tsx] -var obj1; -/*#__PURE__*/ React.createElement("obj1", { - x: 10 -}); // OK +var obj11; +; // OK diff --git a/crates/swc/tests/tsc-references/tsxElementResolution14.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution14.2.minified.js index a68a69cc28c4..ef9ad71bfdd8 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution14.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution14.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution15.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution15.1.normal.js index 790fd3825cd7..a219553a862a 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution15.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution15.1.normal.js @@ -1,5 +1,3 @@ //// [file.tsx] var Obj1; -/*#__PURE__*/ React.createElement(Obj1, { - x: 10 -}); // Error +; // Error diff --git a/crates/swc/tests/tsc-references/tsxElementResolution15.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution15.2.minified.js index a68a69cc28c4..6434a1eb4e85 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution15.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution15.2.minified.js @@ -1 +1,3 @@ //// [file.tsx] +var Obj1; +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution16.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution16.1.normal.js index 24064517b65b..21f219be8f28 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution16.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution16.1.normal.js @@ -1,5 +1,3 @@ //// [file.tsx] -var obj1; -/*#__PURE__*/ React.createElement("obj1", { - x: 10 -}); // Error (JSX.Element is implicit any) +var obj11; +; // Error (JSX.Element is implicit any) diff --git a/crates/swc/tests/tsc-references/tsxElementResolution16.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution16.2.minified.js index a68a69cc28c4..ef9ad71bfdd8 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution16.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution16.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution17.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution17.1.normal.js index fc9aad8cb821..7008f655d8d8 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution17.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution17.1.normal.js @@ -22,5 +22,5 @@ define([ Object.defineProperty(exports, "__esModule", { value: true }); - /*#__PURE__*/ React.createElement(_elements1.MyElement, null); + ; }); diff --git a/crates/swc/tests/tsc-references/tsxElementResolution17.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution17.2.minified.js index e9c42c0d2fc9..bdfd31265741 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution17.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution17.2.minified.js @@ -14,5 +14,5 @@ define([ ], function(require, exports, _elements1) { Object.defineProperty(exports, "__esModule", { value: !0 - }), _elements1.MyElement; + }), ; }); diff --git a/crates/swc/tests/tsc-references/tsxElementResolution18.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution18.1.normal.js index c46189b45142..49bd33e127c0 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution18.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution18.1.normal.js @@ -1,5 +1,3 @@ //// [file1.tsx] // Error under implicit any -/*#__PURE__*/ React.createElement("div", { - n: "x" -}); +
; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution18.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution18.2.minified.js index 19c574bd887a..215687975401 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution18.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution18.2.minified.js @@ -1 +1,2 @@ //// [file1.tsx] +
; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution2.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution2.1.normal.js index a01fc8141a07..04cebbc48af6 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution2.1.normal.js @@ -1,5 +1,5 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("div", null); +
; // OK -/*#__PURE__*/ React.createElement("span", null); +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution2.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution2.2.minified.js index a68a69cc28c4..e18a0efb54fb 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution2.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
, ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution3.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution3.1.normal.js index 310cf527d29c..211d4426031a 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution3.1.normal.js @@ -1,9 +1,5 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("div", { - n: "x" -}); +
; // Error -/*#__PURE__*/ React.createElement("span", { - w: "err" -}); +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution3.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution3.2.minified.js index a68a69cc28c4..a51691722cba 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution3.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
, ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution4.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution4.1.normal.js index d8cd8dc93784..fa520d6cc6bc 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution4.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution4.1.normal.js @@ -1,13 +1,7 @@ //// [file.tsx] // OK -/*#__PURE__*/ React.createElement("div", { - n: "x" -}); +
; // OK -/*#__PURE__*/ React.createElement("span", { - m: "ok" -}); +; // Error -/*#__PURE__*/ React.createElement("span", { - q: "" -}); +; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution4.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution4.2.minified.js index a68a69cc28c4..c5133cc19c21 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution4.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution4.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
, , ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution5.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution5.1.normal.js index 4b9d0bf1e6ac..277cf33f27b2 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution5.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution5.1.normal.js @@ -1,5 +1,3 @@ //// [file1.tsx] // OK, but implicit any -/*#__PURE__*/ React.createElement("div", { - n: "x" -}); +
; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution5.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution5.2.minified.js index 19c574bd887a..215687975401 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution5.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution5.2.minified.js @@ -1 +1,2 @@ //// [file1.tsx] +
; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution6.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution6.1.normal.js index 2336fce0b7a1..cdeb2355f2e4 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution6.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution6.1.normal.js @@ -1,6 +1,4 @@ //// [file.tsx] -var div; +var div1; // Still an error -/*#__PURE__*/ React.createElement("div", { - n: "x" -}); +
; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution6.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution6.2.minified.js index a68a69cc28c4..b70141037b96 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution6.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution6.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution7.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution7.1.normal.js index 6d87450880a5..a28c728b2a2d 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution7.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution7.1.normal.js @@ -1,18 +1,14 @@ //// [file.tsx] (function(my) {})(my || (my = {})); // OK -/*#__PURE__*/ React.createElement(my.div, { - n: "x" -}); +; // Error -/*#__PURE__*/ React.createElement(my.other, null); +; (function(q) { var mine = my; // OK - /*#__PURE__*/ React.createElement(mine.div, { - n: "x" - }); + ; // Error - /*#__PURE__*/ React.createElement(mine.non, null); + ; })(q || (q = {})); var my, q; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution7.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution7.2.minified.js index 7a17146c7938..fdbf21acf691 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution7.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution7.2.minified.js @@ -1,3 +1,3 @@ //// [file.tsx] -var my, q, mine; -my || (my = {}), my.div, my.other, q || (q = {}), (mine = my).div, mine.non; +var my, q; +my || (my = {}), , , q || (q = {}), , ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution8.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution8.1.normal.js index 9a32b947a4ec..61ddd983e8ca 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution8.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution8.1.normal.js @@ -1,20 +1,20 @@ //// [file.tsx] // Error var Div = 3; -/*#__PURE__*/ React.createElement(Div, null); +
; // OK function Fact() { return null; } -/*#__PURE__*/ React.createElement(Fact, null); +; // Error function Fnum() { return 42; } -/*#__PURE__*/ React.createElement(Fnum, null); +; var Obj1; -/*#__PURE__*/ React.createElement(Obj1, null); // OK, prefer construct signatures +; // OK, prefer construct signatures var Obj2; -/*#__PURE__*/ React.createElement(Obj2, null); // Error +; // Error var Obj3; -/*#__PURE__*/ React.createElement(Obj3, null); // Error +; // Error diff --git a/crates/swc/tests/tsc-references/tsxElementResolution8.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution8.2.minified.js index a68a69cc28c4..61dcbf31ab0f 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution8.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution8.2.minified.js @@ -1 +1,9 @@ //// [file.tsx] +var Obj1, Obj2, Obj3; +function Fact() { + return null; +} +function Fnum() { + return 42; +} +
, , , , , ; diff --git a/crates/swc/tests/tsc-references/tsxElementResolution9.1.normal.js b/crates/swc/tests/tsc-references/tsxElementResolution9.1.normal.js index f0c658d59cd7..3c31742d9c0a 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution9.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution9.1.normal.js @@ -1,9 +1,7 @@ //// [file.tsx] var Obj1; -/*#__PURE__*/ React.createElement(Obj1, null); // Error, return type is not an object type +; // Error, return type is not an object type var Obj2; -/*#__PURE__*/ React.createElement(Obj2, null); // Error, return type is not an object type +; // Error, return type is not an object type var Obj3; -/*#__PURE__*/ React.createElement(Obj3, { - x: 42 -}); // OK +; // OK diff --git a/crates/swc/tests/tsc-references/tsxElementResolution9.2.minified.js b/crates/swc/tests/tsc-references/tsxElementResolution9.2.minified.js index a68a69cc28c4..61a269492925 100644 --- a/crates/swc/tests/tsc-references/tsxElementResolution9.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxElementResolution9.2.minified.js @@ -1 +1,3 @@ //// [file.tsx] +var Obj1, Obj2, Obj3; +, , ; diff --git a/crates/swc/tests/tsc-references/tsxEmit1.1.normal.js b/crates/swc/tests/tsc-references/tsxEmit1.1.normal.js index 38591ed8e790..3cc92e5ed957 100644 --- a/crates/swc/tests/tsc-references/tsxEmit1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxEmit1.1.normal.js @@ -2,42 +2,18 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array"; var p; -var selfClosed1 = /*#__PURE__*/ React.createElement("div", null); -var selfClosed2 = /*#__PURE__*/ React.createElement("div", { - x: "1" -}); -var selfClosed3 = /*#__PURE__*/ React.createElement("div", { - x: "1" -}); -var selfClosed4 = /*#__PURE__*/ React.createElement("div", { - x: "1", - y: "0" -}); -var selfClosed5 = /*#__PURE__*/ React.createElement("div", { - x: 0, - y: "0" -}); -var selfClosed6 = /*#__PURE__*/ React.createElement("div", { - x: "1", - y: "0" -}); -var selfClosed7 = /*#__PURE__*/ React.createElement("div", { - x: p, - y: "p" -}); -var openClosed1 = /*#__PURE__*/ React.createElement("div", null); -var openClosed2 = /*#__PURE__*/ React.createElement("div", { - n: "m" -}, "foo"); -var openClosed3 = /*#__PURE__*/ React.createElement("div", { - n: "m" -}, p); -var openClosed4 = /*#__PURE__*/ React.createElement("div", { - n: "m" -}, p < p); -var openClosed5 = /*#__PURE__*/ React.createElement("div", { - n: "m" -}, p > p); +var selfClosed1 =
; +var selfClosed2 =
; +var selfClosed3 =
; +var selfClosed4 =
; +var selfClosed5 =
; +var selfClosed6 =
; +var selfClosed7 =
; +var openClosed1 =
; +var openClosed2 =
foo
; +var openClosed3 =
{p}
; +var openClosed4 =
{p < p}
; +var openClosed5 =
{p > p}
; var SomeClass = /*#__PURE__*/ function() { "use strict"; function SomeClass() { @@ -46,37 +22,33 @@ var SomeClass = /*#__PURE__*/ function() { var _proto = SomeClass.prototype; _proto.f = function f() { var _this = this; - var rewrites1 = /*#__PURE__*/ React.createElement("div", null, function() { + var rewrites1 =
{function() { return _this; - }); - var rewrites2 = /*#__PURE__*/ React.createElement("div", null, [ + }}
; + var rewrites2 =
{[ p ].concat(_to_consumable_array(p), [ p - ])); - var rewrites3 = /*#__PURE__*/ React.createElement("div", null, { + ])}
; + var rewrites3 =
{{ p: p - }); - var rewrites4 = /*#__PURE__*/ React.createElement("div", { - a: function() { - return _this; - } - }); - var rewrites5 = /*#__PURE__*/ React.createElement("div", { - a: [ - p - ].concat(_to_consumable_array(p), [ - p - ]) - }); - var rewrites6 = /*#__PURE__*/ React.createElement("div", { - a: { - p: p - } - }); + }}
; + var rewrites4 =
; + var rewrites5 =
; + var rewrites6 =
; }; return SomeClass; }(); -var whitespace1 = /*#__PURE__*/ React.createElement("div", null, " "); -var whitespace2 = /*#__PURE__*/ React.createElement("div", null, " ", p, " "); -var whitespace3 = /*#__PURE__*/ React.createElement("div", null, p); +var whitespace1 =
; +var whitespace2 =
{p}
; +var whitespace3 =
+ {p} +
; diff --git a/crates/swc/tests/tsc-references/tsxEmit1.2.minified.js b/crates/swc/tests/tsc-references/tsxEmit1.2.minified.js index e8a06ca326f6..dcf26ea4c7cf 100644 --- a/crates/swc/tests/tsc-references/tsxEmit1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxEmit1.2.minified.js @@ -1,3 +1,7 @@ //// [file.tsx] +var p; import "@swc/helpers/_/_class_call_check"; import "@swc/helpers/_/_to_consumable_array"; +
,
,
,
,
,
,
,
,
foo
,
{p}
,
{!1}
,
{!1}
,
,
{p}
,
+ {p} +
; diff --git a/crates/swc/tests/tsc-references/tsxEmit2.1.normal.js b/crates/swc/tests/tsc-references/tsxEmit2.1.normal.js index 65b5743cad71..0884ce4dcaed 100644 --- a/crates/swc/tests/tsc-references/tsxEmit2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxEmit2.1.normal.js @@ -1,17 +1,7 @@ //// [file.tsx] -import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; var p1, p2, p3; -var spreads1 = /*#__PURE__*/ React.createElement("div", p1, p2); -var spreads2 = /*#__PURE__*/ React.createElement("div", p1, p2); -var spreads3 = /*#__PURE__*/ React.createElement("div", _object_spread({ - x: p3 -}, p1), p2); -var spreads4 = /*#__PURE__*/ React.createElement("div", _object_spread_props(_object_spread({}, p1), { - x: p3 -}), p2); -var spreads5 = /*#__PURE__*/ React.createElement("div", _object_spread_props(_object_spread({ - x: p2 -}, p1), { - y: p3 -}), p2); +var spreads1 =
{p2}
; +var spreads2 =
{p2}
; +var spreads3 =
{p2}
; +var spreads4 =
{p2}
; +var spreads5 =
{p2}
; diff --git a/crates/swc/tests/tsc-references/tsxEmit2.2.minified.js b/crates/swc/tests/tsc-references/tsxEmit2.2.minified.js index 48eed89ed72c..6fa565c60dac 100644 --- a/crates/swc/tests/tsc-references/tsxEmit2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxEmit2.2.minified.js @@ -1,13 +1,3 @@ //// [file.tsx] var p1, p2, p3; -import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; -_object_spread({ - x: p3 -}, p1), _object_spread_props(_object_spread({}, p1), { - x: p3 -}), _object_spread_props(_object_spread({ - x: p2 -}, p1), { - y: p3 -}); +
{p2}
,
{p2}
,
{p2}
,
{p2}
,
{p2}
; diff --git a/crates/swc/tests/tsc-references/tsxEmit3.1.normal.js b/crates/swc/tests/tsc-references/tsxEmit3.1.normal.js index 441653975504..0fbdf1f8a1f6 100644 --- a/crates/swc/tests/tsc-references/tsxEmit3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxEmit3.1.normal.js @@ -18,21 +18,21 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; })(M || (M = {})); (function(M) { // Emit M.Foo - Foo, /*#__PURE__*/ React.createElement(Foo, null); + Foo, ; (function(S1) { // Emit M.Foo - Foo, /*#__PURE__*/ React.createElement(Foo, null); + Foo, ; // Emit S.Bar - Bar, /*#__PURE__*/ React.createElement(Bar, null); + Bar, ; })(M.S || (M.S = {})); })(M || (M = {})); (function(M) { // Emit M.S.Bar - S.Bar, /*#__PURE__*/ React.createElement(S.Bar, null); + S.Bar, ; })(M || (M = {})); (function(M) { var M1 = 100; // Emit M_1.Foo - Foo, /*#__PURE__*/ React.createElement(Foo, null); + Foo, ; })(M || (M = {})); var M; diff --git a/crates/swc/tests/tsc-references/tsxEmit3.2.minified.js b/crates/swc/tests/tsc-references/tsxEmit3.2.minified.js index b90f0911964c..9c5cec259bfc 100644 --- a/crates/swc/tests/tsc-references/tsxEmit3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxEmit3.2.minified.js @@ -5,4 +5,4 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; _class_call_check(this, Foo1); }, (M1.S || (M1.S = {})).Bar = function Bar1() { _class_call_check(this, Bar1); -}, Foo, Foo, (M2 = M || (M = {})).S || (M2.S = {}), Foo, Foo, Bar, Bar, M || (M = {}), S.Bar, S.Bar, M || (M = {}), Foo, Foo; +}, M2 = M || (M = {}), Foo, , M2.S || (M2.S = {}), Foo, , Bar, , M || (M = {}), S.Bar, , M || (M = {}), Foo, ; diff --git a/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.1.normal.js b/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.1.normal.js index c4e4ffe19d51..74ab9ad7b24d 100644 --- a/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.1.normal.js @@ -28,7 +28,7 @@ var App = /*#__PURE__*/ function(_React_Component) { } var _proto = App.prototype; _proto.render = function render() { - return /*#__PURE__*/ _react.createElement(_button.Button, null); + return ; }; return Button; }(_react.Component); diff --git a/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.2.minified.js b/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.2.minified.js index 9596dd4f999b..c35aa45d21d1 100644 --- a/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxExternalModuleEmit1.2.minified.js @@ -9,12 +9,14 @@ Object.defineProperty(exports, "__esModule", { return App; } }); -var _call_super = require("@swc/helpers/_/_call_super"), _class_call_check = require("@swc/helpers/_/_class_call_check"), _inherits = require("@swc/helpers/_/_inherits"), _react = /*#__PURE__*/ require("@swc/helpers/_/_interop_require_wildcard")._(require("react")), _button = require("./button"), App = /*#__PURE__*/ function(_React_Component) { +var _call_super = require("@swc/helpers/_/_call_super"), _class_call_check = require("@swc/helpers/_/_class_call_check"), _inherits = require("@swc/helpers/_/_inherits"), _react = /*#__PURE__*/ require("@swc/helpers/_/_interop_require_wildcard")._(require("react")); +require("./button"); +var App = /*#__PURE__*/ function(_React_Component) { function App() { return _class_call_check._(this, App), _call_super._(this, App, arguments); } return _inherits._(App, _React_Component), App.prototype.render = function() { - return _react.createElement(_button.Button, null); + return ; }, Button; -}(_react.Component); +}(/*#__PURE__*/ require("@swc/helpers/_/_interop_require_wildcard")._(require("react")).Component); diff --git a/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.1.normal.js b/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.1.normal.js index 398d51ece8c5..c4da446842cf 100644 --- a/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.1.normal.js @@ -1,8 +1,8 @@ //// [file.tsx] -/*#__PURE__*/ React.createElement(React.Fragment, null); // no whitespace -/*#__PURE__*/ React.createElement(React.Fragment, null); // lots of whitespace -/*#__PURE__*/ React.createElement(React.Fragment, null); // comments in the tags -/*#__PURE__*/ React.createElement(React.Fragment, null, "hi"); // text inside -/*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("span", null, "hi"), /*#__PURE__*/ React.createElement("div", null, "bye")); // children -/*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("span", null, "1"), /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("span", null, "2.1"), /*#__PURE__*/ React.createElement("span", null, "2.2")), /*#__PURE__*/ React.createElement("span", null, "3")); // nested fragments -/*#__PURE__*/ React.createElement(React.Fragment, null, "#"); // # would cause scanning error if not in jsxtext +<>; // no whitespace +<>; // lots of whitespace +<>; // comments in the tags +<>hi; // text inside +<>hi
bye
; // children +<>1<>2.12.23; // nested fragments +<>#; // # would cause scanning error if not in jsxtext diff --git a/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.2.minified.js b/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.2.minified.js index 6d678e6a6251..47b20487a968 100644 --- a/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxFragmentPreserveEmit.2.minified.js @@ -1,2 +1,2 @@ //// [file.tsx] -React.Fragment, React.Fragment, React.Fragment, React.Fragment, React.Fragment, React.Fragment, React.Fragment, React.Fragment; +<>, <>, <>, <>hi, <>hi
bye
, <>1<>2.12.23, <>#; diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType1.1.normal.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType1.1.normal.js index cd7958a16d2a..fe8aff21fd8c 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType1.1.normal.js @@ -1,10 +1,16 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { -//! 5 | return (props) => -//! `---- +var decorator = function decorator(Component) { + return function(props) { + return ; + }; +}; +var decorator2 = function decorator2(Component) { + return function(props) { + return ; + }; +}; +var decorator3 = function decorator3(Component) { + return function(props) { + return ; + }; +}; diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType1.2.minified.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType1.2.minified.js index cd7958a16d2a..a68a69cc28c4 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType1.2.minified.js @@ -1,10 +1 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { -//! 5 | return (props) => -//! `---- diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType2.1.normal.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType2.1.normal.js index d58cb639d753..458e52b47a24 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType2.1.normal.js @@ -1,10 +1,6 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { -//! 5 | return (props) => -//! `---- +var decorator4 = function decorator4(Component) { + return function(props) { + return ; + }; +}; diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType2.2.minified.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType2.2.minified.js index d58cb639d753..a68a69cc28c4 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType2.2.minified.js @@ -1,10 +1 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { -//! 5 | return (props) => -//! `---- diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType7.1.normal.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType7.1.normal.js index b351c598eb1e..94cfd3ed6c4f 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType7.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType7.1.normal.js @@ -1,10 +1,7 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | declare function Component(props: T) : JSX.Element; -//! 5 | const decorator = function (props: U) { -//! `---- +var decorator = function decorator(props) { + return ; +}; +var decorator1 = function decorator1(props) { + return ; +}; diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType7.2.minified.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType7.2.minified.js index b351c598eb1e..a68a69cc28c4 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType7.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType7.2.minified.js @@ -1,10 +1 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | declare function Component(props: T) : JSX.Element; -//! 5 | const decorator = function (props: U) { -//! `---- diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType8.1.normal.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType8.1.normal.js index b351c598eb1e..f7eaaf7c3b5f 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType8.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType8.1.normal.js @@ -1,10 +1,7 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | declare function Component(props: T) : JSX.Element; -//! 5 | const decorator = function (props: U) { -//! `---- +var decorator = function decorator(props) { + return ; +}; +var decorator1 = function decorator1(props) { + return ; +}; diff --git a/crates/swc/tests/tsc-references/tsxGenericAttributesType8.2.minified.js b/crates/swc/tests/tsc-references/tsxGenericAttributesType8.2.minified.js index b351c598eb1e..a68a69cc28c4 100644 --- a/crates/swc/tests/tsc-references/tsxGenericAttributesType8.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxGenericAttributesType8.2.minified.js @@ -1,10 +1 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | declare function Component(props: T) : JSX.Element; -//! 5 | const decorator = function (props: U) { -//! `---- diff --git a/crates/swc/tests/tsc-references/tsxInArrowFunction.1.normal.js b/crates/swc/tests/tsc-references/tsxInArrowFunction.1.normal.js index 8a24cc2e9470..bc7080bd7677 100644 --- a/crates/swc/tests/tsc-references/tsxInArrowFunction.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxInArrowFunction.1.normal.js @@ -1,25 +1,17 @@ //// [tsxInArrowFunction.tsx] // didn't work -/*#__PURE__*/ React.createElement("div", null, function() { - return /*#__PURE__*/ React.createElement("div", { - text: "wat" - }); -}); +
{function() { + return
; +}}
; // didn't work -/*#__PURE__*/ React.createElement("div", null, function(x) { - return /*#__PURE__*/ React.createElement("div", { - text: "wat" - }); -}); +
{function(x) { + return
; +}}
; // worked -/*#__PURE__*/ React.createElement("div", null, function() { - return /*#__PURE__*/ React.createElement("div", { - text: "wat" - }); -}); +
{function() { + return
; +}}
; // worked (!) -/*#__PURE__*/ React.createElement("div", null, function() { - return /*#__PURE__*/ React.createElement("div", { - text: "wat" - }); -}); +
{function() { + return
; +}}
; diff --git a/crates/swc/tests/tsc-references/tsxInArrowFunction.2.minified.js b/crates/swc/tests/tsc-references/tsxInArrowFunction.2.minified.js index 640164e4f5b2..282dce92e622 100644 --- a/crates/swc/tests/tsc-references/tsxInArrowFunction.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxInArrowFunction.2.minified.js @@ -1 +1,10 @@ //// [tsxInArrowFunction.tsx] +
{function() { + return
; +}}
,
{function(x) { + return
; +}}
,
{function() { + return
; +}}
,
{function() { + return
; +}}
; diff --git a/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.1.normal.js b/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.1.normal.js index a3c1a7d81f0e..41a453cca523 100644 --- a/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.1.normal.js @@ -1,5 +1,3 @@ //// [tsxIntrinsicAttributeErrors.tsx] var E; -/*#__PURE__*/ React.createElement(E, { - x: 10 -}); +; diff --git a/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.2.minified.js b/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.2.minified.js index 391e41e23d79..41a453cca523 100644 --- a/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxIntrinsicAttributeErrors.2.minified.js @@ -1 +1,3 @@ //// [tsxIntrinsicAttributeErrors.tsx] +var E; +; diff --git a/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.1.normal.js b/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.1.normal.js index 4f63f92fb2f5..8ad60eade8a2 100644 --- a/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.1.normal.js @@ -19,33 +19,12 @@ Component.propTypes = { Component.defaultProps = { foo: 42 }; -var a = /*#__PURE__*/ React.createElement(Component, { - foo: 12, - bar: "yes", - baz: "yeah" -}); -var b = /*#__PURE__*/ React.createElement(Component, { - foo: 12 -}); // Error, missing required prop bar -var c = /*#__PURE__*/ React.createElement(Component, { - bar: "yes", - baz: "yeah" -}); -var d = /*#__PURE__*/ React.createElement(Component, { - bar: "yes", - baz: "yo", - bat: "ohno" -}); // Error, baz not a valid prop -var e = /*#__PURE__*/ React.createElement(Component, { - foo: 12, - bar: null, - baz: "cool" -}); // bar is nullable/undefinable since it's not marked `isRequired` -var f = /*#__PURE__*/ React.createElement(Component, { - foo: 12, - bar: "yeah", - baz: null -}); // Error, baz is _not_ nullable/undefinable since it's marked `isRequired` +var a = ; +var b = ; // Error, missing required prop bar +var c = ; +var d = ; // Error, baz not a valid prop +var e = ; // bar is nullable/undefinable since it's not marked `isRequired` +var f = ; // Error, baz is _not_ nullable/undefinable since it's marked `isRequired` var JustPropTypes = /*#__PURE__*/ function(ReactComponent1) { "use strict"; _inherits(JustPropTypes, ReactComponent1); @@ -59,21 +38,10 @@ JustPropTypes.propTypes = { foo: PropTypes.number, bar: PropTypes.node.isRequired }; -var g = /*#__PURE__*/ React.createElement(JustPropTypes, { - foo: 12, - bar: "ok" -}); -var h = /*#__PURE__*/ React.createElement(JustPropTypes, { - foo: "no" -}); // error, wrong type -var i = /*#__PURE__*/ React.createElement(JustPropTypes, { - foo: null, - bar: "ok" -}); -var j = /*#__PURE__*/ React.createElement(JustPropTypes, { - foo: 12, - bar: null -}); // error, bar is required +var g = ; +var h = ; // error, wrong type +var i = ; +var j = ; // error, bar is required var JustDefaultProps = /*#__PURE__*/ function(ReactComponent1) { "use strict"; _inherits(JustDefaultProps, ReactComponent1); @@ -86,16 +54,9 @@ var JustDefaultProps = /*#__PURE__*/ function(ReactComponent1) { JustDefaultProps.defaultProps = { foo: 42 }; -var k = /*#__PURE__*/ React.createElement(JustDefaultProps, { - foo: 12 -}); -var l = /*#__PURE__*/ React.createElement(JustDefaultProps, { - foo: 12, - bar: "ok" -}); // error, no prop named bar -var m = /*#__PURE__*/ React.createElement(JustDefaultProps, { - foo: "no" -}); // error, wrong type +var k = ; +var l = ; // error, no prop named bar +var m = ; // error, wrong type var BothWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent1) { "use strict"; _inherits(BothWithSpecifiedGeneric, ReactComponent1); @@ -113,33 +74,12 @@ BothWithSpecifiedGeneric.propTypes = { BothWithSpecifiedGeneric.defaultProps = { foo: "yo" }; -var n = /*#__PURE__*/ React.createElement(BothWithSpecifiedGeneric, { - foo: "fine", - bar: "yes", - baz: 12 -}); -var o = /*#__PURE__*/ React.createElement(BothWithSpecifiedGeneric, { - foo: "no" -}); // Error, missing required prop bar -var p = /*#__PURE__*/ React.createElement(BothWithSpecifiedGeneric, { - bar: "yes", - baz: 12 -}); -var q = /*#__PURE__*/ React.createElement(BothWithSpecifiedGeneric, { - bar: "yes", - baz: 12, - bat: "ohno" -}); // Error, baz not a valid prop -var r = /*#__PURE__*/ React.createElement(BothWithSpecifiedGeneric, { - foo: "no", - bar: null, - baz: 0 -}); // bar is nullable/undefinable since it's not marked `isRequired` -var s = /*#__PURE__*/ React.createElement(BothWithSpecifiedGeneric, { - foo: "eh", - bar: "yeah", - baz: null -}); // Error, baz is _not_ nullable/undefinable since it's marked `isRequired` +var n = ; +var o = ; // Error, missing required prop bar +var p = ; +var q = ; // Error, baz not a valid prop +var r = ; // bar is nullable/undefinable since it's not marked `isRequired` +var s = ; // Error, baz is _not_ nullable/undefinable since it's marked `isRequired` var JustPropTypesWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent1) { "use strict"; _inherits(JustPropTypesWithSpecifiedGeneric, ReactComponent1); @@ -153,21 +93,10 @@ JustPropTypesWithSpecifiedGeneric.propTypes = { foo: PropTypes.string, bar: PropTypes.node.isRequired }; -var t = /*#__PURE__*/ React.createElement(JustPropTypesWithSpecifiedGeneric, { - foo: "nice", - bar: "ok" -}); -var u = /*#__PURE__*/ React.createElement(JustPropTypesWithSpecifiedGeneric, { - foo: 12 -}); // error, wrong type -var v = /*#__PURE__*/ React.createElement(JustPropTypesWithSpecifiedGeneric, { - foo: null, - bar: "ok" -}); // generic overrides propTypes required-ness, null isn't valid -var w = /*#__PURE__*/ React.createElement(JustPropTypesWithSpecifiedGeneric, { - foo: "cool", - bar: null -}); // error, bar is required +var t = ; +var u = ; // error, wrong type +var v = ; // generic overrides propTypes required-ness, null isn't valid +var w = ; // error, bar is required var JustDefaultPropsWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent1) { "use strict"; _inherits(JustDefaultPropsWithSpecifiedGeneric, ReactComponent1); @@ -180,14 +109,7 @@ var JustDefaultPropsWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent JustDefaultPropsWithSpecifiedGeneric.defaultProps = { foo: "no" }; -var x = /*#__PURE__*/ React.createElement(JustDefaultPropsWithSpecifiedGeneric, { - foo: "eh" -}); -var y = /*#__PURE__*/ React.createElement(JustDefaultPropsWithSpecifiedGeneric, { - foo: "no", - bar: "ok" -}); // error, no prop named bar -var z = /*#__PURE__*/ React.createElement(JustDefaultPropsWithSpecifiedGeneric, { - foo: 12 -}); // error, wrong type -var aa = /*#__PURE__*/ React.createElement(JustDefaultPropsWithSpecifiedGeneric, null); +var x = ; +var y = ; // error, no prop named bar +var z = ; // error, wrong type +var aa = ; diff --git a/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.2.minified.js b/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.2.minified.js index 596a59056f33..5bcf5e82ddbe 100644 --- a/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxLibraryManagedAttributes.2.minified.js @@ -14,22 +14,26 @@ Component.propTypes = { baz: PropTypes.string.isRequired }, Component.defaultProps = { foo: 42 -}, /*#__PURE__*/ function(ReactComponent1) { +}, , , , , , ; +var JustPropTypes = /*#__PURE__*/ function(ReactComponent1) { function JustPropTypes() { return _class_call_check(this, JustPropTypes), _call_super(this, JustPropTypes, arguments); } return _inherits(JustPropTypes, ReactComponent1), JustPropTypes; -}(ReactComponent).propTypes = { +}(ReactComponent); +JustPropTypes.propTypes = { foo: PropTypes.number, bar: PropTypes.node.isRequired -}, /*#__PURE__*/ function(ReactComponent1) { +}, , , , ; +var JustDefaultProps = /*#__PURE__*/ function(ReactComponent1) { function JustDefaultProps() { return _class_call_check(this, JustDefaultProps), _call_super(this, JustDefaultProps, arguments); } return _inherits(JustDefaultProps, ReactComponent1), JustDefaultProps; -}(ReactComponent).defaultProps = { +}(ReactComponent); +JustDefaultProps.defaultProps = { foo: 42 -}; +}, , , ; var BothWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent1) { function BothWithSpecifiedGeneric() { return _class_call_check(this, BothWithSpecifiedGeneric), _call_super(this, BothWithSpecifiedGeneric, arguments); @@ -42,19 +46,23 @@ BothWithSpecifiedGeneric.propTypes = { baz: PropTypes.number.isRequired }, BothWithSpecifiedGeneric.defaultProps = { foo: "yo" -}, /*#__PURE__*/ function(ReactComponent1) { +}, , , , , , ; +var JustPropTypesWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent1) { function JustPropTypesWithSpecifiedGeneric() { return _class_call_check(this, JustPropTypesWithSpecifiedGeneric), _call_super(this, JustPropTypesWithSpecifiedGeneric, arguments); } return _inherits(JustPropTypesWithSpecifiedGeneric, ReactComponent1), JustPropTypesWithSpecifiedGeneric; -}(ReactComponent).propTypes = { +}(ReactComponent); +JustPropTypesWithSpecifiedGeneric.propTypes = { foo: PropTypes.string, bar: PropTypes.node.isRequired -}, /*#__PURE__*/ function(ReactComponent1) { +}, , , , ; +var JustDefaultPropsWithSpecifiedGeneric = /*#__PURE__*/ function(ReactComponent1) { function JustDefaultPropsWithSpecifiedGeneric() { return _class_call_check(this, JustDefaultPropsWithSpecifiedGeneric), _call_super(this, JustDefaultPropsWithSpecifiedGeneric, arguments); } return _inherits(JustDefaultPropsWithSpecifiedGeneric, ReactComponent1), JustDefaultPropsWithSpecifiedGeneric; -}(ReactComponent).defaultProps = { +}(ReactComponent); +JustDefaultPropsWithSpecifiedGeneric.defaultProps = { foo: "no" -}; +}, , , , ; diff --git a/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.1.normal.js b/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.1.normal.js index 116bd10656bb..cc4b240e98f0 100644 --- a/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.1.normal.js @@ -1,15 +1,3 @@ //// [a.tsx] -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[2:1] -//! 1 | -//! 2 | const a = ; -//! : ^^^^^^^^ -//! 3 | const b = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[3:1] -//! 1 | -//! 2 | const a = ; -//! 3 | const b = ; -//! : ^^^^^^^^^^ -//! `---- +var a = ; +var b = ; diff --git a/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.2.minified.js b/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.2.minified.js index 116bd10656bb..128fa2cf8909 100644 --- a/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxNamespacedAttributeName1.2.minified.js @@ -1,15 +1,2 @@ //// [a.tsx] -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[2:1] -//! 1 | -//! 2 | const a = ; -//! : ^^^^^^^^ -//! 3 | const b = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[3:1] -//! 1 | -//! 2 | const a = ; -//! 3 | const b = ; -//! : ^^^^^^^^^^ -//! `---- +, ; diff --git a/crates/swc/tests/tsc-references/tsxNamespacedTagName1.1.normal.js b/crates/swc/tests/tsc-references/tsxNamespacedTagName1.1.normal.js index d8127eb57c04..c1cec549a790 100644 --- a/crates/swc/tests/tsc-references/tsxNamespacedTagName1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxNamespacedTagName1.1.normal.js @@ -1,36 +1,5 @@ //// [a.tsx] -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[2:1] -//! 1 | -//! 2 | const a = ; -//! : ^^^^^^^^ -//! 3 | const b = ; -//! 4 | const c = ; -//! 5 | const d = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[3:1] -//! 1 | -//! 2 | const a = ; -//! 3 | const b = ; -//! : ^^^^^^^^^^ -//! 4 | const c = ; -//! 5 | const d = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[4:1] -//! 1 | -//! 2 | const a = ; -//! 3 | const b = ; -//! 4 | const c = ; -//! : ^^^^^ -//! 5 | const d = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[5:1] -//! 2 | const a = ; -//! 3 | const b = ; -//! 4 | const c = ; -//! 5 | const d = ; -//! : ^^^^^ -//! `---- +var a = ; +var b = ; +var c = ; +var d = ; diff --git a/crates/swc/tests/tsc-references/tsxNamespacedTagName1.2.minified.js b/crates/swc/tests/tsc-references/tsxNamespacedTagName1.2.minified.js index d8127eb57c04..07c30c0ee7d7 100644 --- a/crates/swc/tests/tsc-references/tsxNamespacedTagName1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxNamespacedTagName1.2.minified.js @@ -1,36 +1,2 @@ //// [a.tsx] -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[2:1] -//! 1 | -//! 2 | const a = ; -//! : ^^^^^^^^ -//! 3 | const b = ; -//! 4 | const c = ; -//! 5 | const d = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[3:1] -//! 1 | -//! 2 | const a = ; -//! 3 | const b = ; -//! : ^^^^^^^^^^ -//! 4 | const c = ; -//! 5 | const d = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[4:1] -//! 1 | -//! 2 | const a = ; -//! 3 | const b = ; -//! 4 | const c = ; -//! : ^^^^^ -//! 5 | const d = ; -//! `---- -//! x JSX Namespace is disabled by default because react does not support it yet. You can specify jsc.transform.react.throwIfNamespace to false to override default behavior -//! ,-[5:1] -//! 2 | const a = ; -//! 3 | const b = ; -//! 4 | const c = ; -//! 5 | const d = ; -//! : ^^^^^ -//! `---- +, , , ; diff --git a/crates/swc/tests/tsc-references/tsxNoJsx.1.normal.js b/crates/swc/tests/tsc-references/tsxNoJsx.1.normal.js index f6bb82021b4c..acc10b629863 100644 --- a/crates/swc/tests/tsc-references/tsxNoJsx.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxNoJsx.1.normal.js @@ -1,2 +1,2 @@ //// [tsxNoJsx.tsx] -/*#__PURE__*/ React.createElement("nope", null); +; diff --git a/crates/swc/tests/tsc-references/tsxNoJsx.2.minified.js b/crates/swc/tests/tsc-references/tsxNoJsx.2.minified.js index 3320b929581b..acc10b629863 100644 --- a/crates/swc/tests/tsc-references/tsxNoJsx.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxNoJsx.2.minified.js @@ -1 +1,2 @@ //// [tsxNoJsx.tsx] +; diff --git a/crates/swc/tests/tsc-references/tsxOpeningClosingNames.1.normal.js b/crates/swc/tests/tsc-references/tsxOpeningClosingNames.1.normal.js index 83b739453e8b..eae772483b0a 100644 --- a/crates/swc/tests/tsc-references/tsxOpeningClosingNames.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxOpeningClosingNames.1.normal.js @@ -1,2 +1,2 @@ //// [file.tsx] -/*#__PURE__*/ React.createElement(A.B.C.D, null, "foo"); +foo; diff --git a/crates/swc/tests/tsc-references/tsxOpeningClosingNames.2.minified.js b/crates/swc/tests/tsc-references/tsxOpeningClosingNames.2.minified.js index f87f3d02fd78..eae772483b0a 100644 --- a/crates/swc/tests/tsc-references/tsxOpeningClosingNames.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxOpeningClosingNames.2.minified.js @@ -1,2 +1,2 @@ //// [file.tsx] -A.B.C.D; +foo; diff --git a/crates/swc/tests/tsc-references/tsxParseTests1.1.normal.js b/crates/swc/tests/tsc-references/tsxParseTests1.1.normal.js index 3abf1487615e..888c441adb7b 100644 --- a/crates/swc/tests/tsc-references/tsxParseTests1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxParseTests1.1.normal.js @@ -1,2 +1,2 @@ //// [file.tsx] -var x = /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("span", null, /*#__PURE__*/ React.createElement("div", null)))); +var x =
; diff --git a/crates/swc/tests/tsc-references/tsxParseTests1.2.minified.js b/crates/swc/tests/tsc-references/tsxParseTests1.2.minified.js index a68a69cc28c4..db6bc6e51e63 100644 --- a/crates/swc/tests/tsc-references/tsxParseTests1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxParseTests1.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
; diff --git a/crates/swc/tests/tsc-references/tsxParseTests2.1.normal.js b/crates/swc/tests/tsc-references/tsxParseTests2.1.normal.js index b84a53d1ce77..c5f472a9e517 100644 --- a/crates/swc/tests/tsc-references/tsxParseTests2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxParseTests2.1.normal.js @@ -1,2 +1,2 @@ //// [file.tsx] -var x = /*#__PURE__*/ React.createElement(/**/ "div", null); +var x =
; diff --git a/crates/swc/tests/tsc-references/tsxParseTests2.2.minified.js b/crates/swc/tests/tsc-references/tsxParseTests2.2.minified.js index a68a69cc28c4..5bb92f2200df 100644 --- a/crates/swc/tests/tsc-references/tsxParseTests2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxParseTests2.2.minified.js @@ -1 +1,2 @@ //// [file.tsx] +
; diff --git a/crates/swc/tests/tsc-references/tsxPreserveEmit1.1.normal.js b/crates/swc/tests/tsc-references/tsxPreserveEmit1.1.normal.js index 21df9d3e7f41..18823d48f521 100644 --- a/crates/swc/tests/tsc-references/tsxPreserveEmit1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxPreserveEmit1.1.normal.js @@ -15,19 +15,18 @@ define([ define([ "require", "exports", - "react", "react-router" -], function(require, exports, _react, _reactrouter) { +], function(require, exports, _reactrouter) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Route = _reactrouter.Route; - var routes1 = /*#__PURE__*/ _react.createElement(Route, null); + var routes1 = ; (function(M) {})(M || (M = {})); (function(M) { // Should emit 'M.X' in both opening and closing tags - var y = /*#__PURE__*/ _react.createElement(X, null); + var y = ; })(M || (M = {})); var M; }); diff --git a/crates/swc/tests/tsc-references/tsxPreserveEmit1.2.minified.js b/crates/swc/tests/tsc-references/tsxPreserveEmit1.2.minified.js index e08b93bc3891..9237fd803129 100644 --- a/crates/swc/tests/tsc-references/tsxPreserveEmit1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxPreserveEmit1.2.minified.js @@ -10,11 +10,11 @@ define([ define([ "require", "exports", - "react", "react-router" -], function(require, exports, _react, _reactrouter) { - var M; +], function(require, exports, _reactrouter) { Object.defineProperty(exports, "__esModule", { value: !0 - }), _reactrouter.Route, M || (M = {}), M || (M = {}), X; + }); + var M, Route = _reactrouter.Route; + , M || (M = {}), M || (M = {}), ; }); diff --git a/crates/swc/tests/tsc-references/tsxPreserveEmit2.1.normal.js b/crates/swc/tests/tsc-references/tsxPreserveEmit2.1.normal.js index d34fa8bab6d5..1187cb66d478 100644 --- a/crates/swc/tests/tsc-references/tsxPreserveEmit2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxPreserveEmit2.1.normal.js @@ -10,5 +10,5 @@ define([ ], function(require) { "use strict"; var Route; - var routes1 = /*#__PURE__*/ React.createElement(Route, null); + var routes1 = ; }); diff --git a/crates/swc/tests/tsc-references/tsxPreserveEmit2.2.minified.js b/crates/swc/tests/tsc-references/tsxPreserveEmit2.2.minified.js index 80cf8275d5a4..dedc940831ef 100644 --- a/crates/swc/tests/tsc-references/tsxPreserveEmit2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxPreserveEmit2.2.minified.js @@ -5,4 +5,7 @@ define([ //// [test.tsx] define([ "require" -], function(require) {}); +], function(require) { + var Route; + ; +}); diff --git a/crates/swc/tests/tsc-references/tsxPreserveEmit3.1.normal.js b/crates/swc/tests/tsc-references/tsxPreserveEmit3.1.normal.js index e154042f8208..e907d919c8f6 100644 --- a/crates/swc/tests/tsc-references/tsxPreserveEmit3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxPreserveEmit3.1.normal.js @@ -31,9 +31,8 @@ define([ // This import should be elided define([ "require", - "exports", - "./test" -], function(require, exports, _test) { + "exports" +], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true diff --git a/crates/swc/tests/tsc-references/tsxPreserveEmit3.2.minified.js b/crates/swc/tests/tsc-references/tsxPreserveEmit3.2.minified.js index 5e24c2d5fcda..c6c2aa8d45ef 100644 --- a/crates/swc/tests/tsc-references/tsxPreserveEmit3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxPreserveEmit3.2.minified.js @@ -24,9 +24,8 @@ define([ //// [react-consumer.tsx] define([ "require", - "exports", - "./test" -], function(require, exports, _test) { + "exports" +], function(require, exports) { Object.defineProperty(exports, "__esModule", { value: !0 }); diff --git a/crates/swc/tests/tsc-references/tsxReactEmit8.1.normal.js b/crates/swc/tests/tsc-references/tsxReactEmit8.1.normal.js deleted file mode 100644 index 74399f53ebbf..000000000000 --- a/crates/swc/tests/tsc-references/tsxReactEmit8.1.normal.js +++ /dev/null @@ -1,6 +0,0 @@ -//// [tsxReactEmit8.tsx] -/// -/*#__PURE__*/ React.createElement("div", null, "1"); -/*#__PURE__*/ React.createElement("div", { - key: "key-attr" -}, "2"); diff --git a/crates/swc/tests/tsc-references/tsxReactEmit8.2.minified.js b/crates/swc/tests/tsc-references/tsxReactEmit8.2.minified.js deleted file mode 100644 index b4a77ef0f778..000000000000 --- a/crates/swc/tests/tsc-references/tsxReactEmit8.2.minified.js +++ /dev/null @@ -1 +0,0 @@ -//// [tsxReactEmit8.tsx] diff --git a/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx-dev.1.normal.js b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx-dev.1.normal.js new file mode 100644 index 000000000000..46911ade90e4 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx-dev.1.normal.js @@ -0,0 +1,17 @@ +//// [tsxReactEmit8.tsx] +/// +/*#__PURE__*/ import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime"; +_jsxDEV("div", { + children: "1" +}, void 0, false, { + fileName: "tsxReactEmit8.tsx", + lineNumber: 3, + columnNumber: 1 +}, this); +/*#__PURE__*/ _jsxDEV("div", { + children: "2" +}, "key-attr", false, { + fileName: "tsxReactEmit8.tsx", + lineNumber: 4, + columnNumber: 1 +}, this); diff --git a/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx-dev.2.minified.js b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx-dev.2.minified.js new file mode 100644 index 000000000000..88ad2febee67 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx-dev.2.minified.js @@ -0,0 +1,2 @@ +//// [tsxReactEmit8.tsx] +import "react/jsx-dev-runtime"; diff --git a/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx.1.normal.js b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx.1.normal.js new file mode 100644 index 000000000000..fbbe485b57f9 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx.1.normal.js @@ -0,0 +1,9 @@ +//// [tsxReactEmit8.tsx] +/// +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { + children: "1" +}); +/*#__PURE__*/ _jsx("div", { + children: "2" +}, "key-attr"); diff --git a/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx.2.minified.js b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx.2.minified.js new file mode 100644 index 000000000000..ac22e4d44fee --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxReactEmit8_react-jsx.2.minified.js @@ -0,0 +1,2 @@ +//// [tsxReactEmit8.tsx] +import "react/jsx-runtime"; diff --git a/crates/swc/tests/tsc-references/tsxSfcReturnNull.1.normal.js b/crates/swc/tests/tsc-references/tsxSfcReturnNull.1.normal.js index bfec077a8e66..c0abd2bb84eb 100644 --- a/crates/swc/tests/tsc-references/tsxSfcReturnNull.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSfcReturnNull.1.normal.js @@ -1,19 +1,14 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var Foo = function(props) { return null; }; function Greet(x) { return null; } - var foo = /*#__PURE__*/ _react.createElement(Foo, null); - var G = /*#__PURE__*/ _react.createElement(Greet, null); + var foo = ; + var G = ; }); diff --git a/crates/swc/tests/tsc-references/tsxSfcReturnNull.2.minified.js b/crates/swc/tests/tsc-references/tsxSfcReturnNull.2.minified.js index 7657cb32d106..ff1b8ca54719 100644 --- a/crates/swc/tests/tsc-references/tsxSfcReturnNull.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSfcReturnNull.2.minified.js @@ -1,10 +1,12 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { + var Foo = function(props) { + return null; + }; + function Greet(x) { + return null; + } + , ; }); diff --git a/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.1.normal.js b/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.1.normal.js index bfec077a8e66..c0abd2bb84eb 100644 --- a/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.1.normal.js @@ -1,19 +1,14 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var Foo = function(props) { return null; }; function Greet(x) { return null; } - var foo = /*#__PURE__*/ _react.createElement(Foo, null); - var G = /*#__PURE__*/ _react.createElement(Greet, null); + var foo = ; + var G = ; }); diff --git a/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.2.minified.js b/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.2.minified.js index 7657cb32d106..ff1b8ca54719 100644 --- a/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSfcReturnNullStrictNullChecks.2.minified.js @@ -1,10 +1,12 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { + var Foo = function(props) { + return null; + }; + function Greet(x) { + return null; + } + , ; }); diff --git a/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.1.normal.js b/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.1.normal.js index f1c786cdba3e..ab087f26e91d 100644 --- a/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.1.normal.js @@ -1,13 +1,8 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var Foo = function(props) { return undefined; }; @@ -15,6 +10,6 @@ define([ return undefined; } // Error - var foo = /*#__PURE__*/ _react.createElement(Foo, null); - var G = /*#__PURE__*/ _react.createElement(Greet, null); + var foo = ; + var G = ; }); diff --git a/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.2.minified.js b/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.2.minified.js index 7657cb32d106..b3777c89078e 100644 --- a/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSfcReturnUndefinedStrictNullChecks.2.minified.js @@ -1,10 +1,8 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { + var Foo = function(props) {}; + function Greet(x) {} + , ; }); diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.1.normal.js index b1427fbb94e0..8e8ab98f43f1 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.1.normal.js @@ -1,10 +1,13 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + var condition1; + if (condition1) { + return ; + } else { + return ; + } +} +function ChildComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.2.minified.js index b1427fbb94e0..c13b3f6297f4 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution13.2.minified.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return ; +} +function ChildComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.1.normal.js index b1427fbb94e0..064a1886cbe8 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.1.normal.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return(); +} +function AnotherComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.2.minified.js index b1427fbb94e0..20216fcfa5d9 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution14.2.minified.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return ; +} +function AnotherComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.1.normal.js index b1427fbb94e0..f67615bfb060 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.1.normal.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return ; +} +function AnotherComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.2.minified.js index b1427fbb94e0..f67615bfb060 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution15.2.minified.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return ; +} +function AnotherComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.1.normal.js index b1427fbb94e0..5b78b2f51267 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.1.normal.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return(); +} +function AnotherComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.2.minified.js index b1427fbb94e0..a41a3ac26281 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution16.2.minified.js @@ -1,10 +1,8 @@ //// [file.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | interface ComponentProps { -//! 5 | property1: string; -//! `---- +export default function Component(props) { + return ; +} +function AnotherComponent(param) { + var property1 = param.property1; + return {property1}; +} diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.1.normal.js index e59d6e4a667e..ba32f4b0b78c 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.1.normal.js @@ -11,9 +11,9 @@ export var Empty = /*#__PURE__*/ function(_React_Component) { } var _proto = Empty.prototype; _proto.render = function render() { - return /*#__PURE__*/ React.createElement("div", null, "Hello"); + return
Hello
; }; return Empty; }(React.Component); // OK -var unionedSpread = /*#__PURE__*/ React.createElement(Empty, obj); +var unionedSpread = ; diff --git a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.2.minified.js index 3d2f57b39b9c..fb1ba2b5f213 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadAttributesResolution17.2.minified.js @@ -7,7 +7,7 @@ export var Empty = /*#__PURE__*/ function(_React_Component) { return _class_call_check(this, Empty), _call_super(this, Empty, arguments); } return _inherits(Empty, _React_Component), Empty.prototype.render = function() { - return React.createElement("div", null, "Hello"); + return
Hello
; }, Empty; }(React.Component); -obj; +; diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildren.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildren.1.normal.js index 38d4a066958e..bdad5eb82784 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadChildren.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadChildren.1.normal.js @@ -1,19 +1,14 @@ //// [tsxSpreadChildren.tsx] -import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array"; function Todo(prop) { - return /*#__PURE__*/ React.createElement("div", null, prop.key.toString() + prop.todo); + return
{prop.key.toString() + prop.todo}
; } function TodoList(param) { var todos = param.todos; - return /*#__PURE__*/ React.createElement.apply(React, [ - "div", - null - ].concat(_to_consumable_array(todos.map(function(todo) { - return /*#__PURE__*/ React.createElement(Todo, { - key: todo.id, - todo: todo.todo - }); - })))); + return
+ {...todos.map(function(todo) { + return ; + })} +
; } var x; -/*#__PURE__*/ React.createElement(TodoList, x); +; diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildren.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildren.2.minified.js index 3138c5253e65..e4e7f7773506 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadChildren.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadChildren.2.minified.js @@ -1,2 +1,14 @@ //// [tsxSpreadChildren.tsx] -import "@swc/helpers/_/_to_consumable_array"; +var x; +function Todo(prop) { + return
{prop.key.toString() + prop.todo}
; +} +function TodoList(param) { + var todos = param.todos; + return
+ {...todos.map(function(todo) { + return ; + })} +
; +} +; diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).1.normal.js index 563691055d94..3cb21bab56a7 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).1.normal.js @@ -1,19 +1,29 @@ //// [tsxSpreadChildrenInvalidType.tsx] +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import { jsx as _jsx } from "react/jsx-runtime"; function Todo(prop) { - return /*#__PURE__*/ React.createElement("div", null, prop.key.toString() + prop.todo); + return /*#__PURE__*/ _jsx("div", { + children: prop.key.toString() + prop.todo + }); } function TodoList({ todos }) { - return /*#__PURE__*/ React.createElement("div", null, .../*#__PURE__*/ React.createElement(Todo, { - key: todos[0].id, - todo: todos[0].todo - })); + return /*#__PURE__*/ _jsx("div", { + children: [ + .../*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id) + ] + }); } function TodoListNoError({ todos }) { // any is not checked - return /*#__PURE__*/ React.createElement("div", null, .../*#__PURE__*/ React.createElement(Todo, { - key: todos[0].id, - todo: todos[0].todo - })); + return /*#__PURE__*/ _jsx("div", { + children: [ + .../*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id) + ] + }); } let x; -/*#__PURE__*/ React.createElement(TodoList, x); +/*#__PURE__*/ _jsx(TodoList, _object_spread({}, x)); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).2.minified.js index 240e855a3c76..4d0bfa74b392 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015).2.minified.js @@ -1 +1,5 @@ //// [tsxSpreadChildrenInvalidType.tsx] +let x; +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import "react/jsx-runtime"; +_object_spread({}, x); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react-jsx.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react-jsx.1.normal.js new file mode 100644 index 000000000000..3cb21bab56a7 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react-jsx.1.normal.js @@ -0,0 +1,29 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import { jsx as _jsx } from "react/jsx-runtime"; +function Todo(prop) { + return /*#__PURE__*/ _jsx("div", { + children: prop.key.toString() + prop.todo + }); +} +function TodoList({ todos }) { + return /*#__PURE__*/ _jsx("div", { + children: [ + .../*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id) + ] + }); +} +function TodoListNoError({ todos }) { + // any is not checked + return /*#__PURE__*/ _jsx("div", { + children: [ + .../*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id) + ] + }); +} +let x; +/*#__PURE__*/ _jsx(TodoList, _object_spread({}, x)); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react-jsx.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react-jsx.2.minified.js new file mode 100644 index 000000000000..4d0bfa74b392 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react-jsx.2.minified.js @@ -0,0 +1,5 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +let x; +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import "react/jsx-runtime"; +_object_spread({}, x); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react.1.normal.js new file mode 100644 index 000000000000..563691055d94 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react.1.normal.js @@ -0,0 +1,19 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +function Todo(prop) { + return /*#__PURE__*/ React.createElement("div", null, prop.key.toString() + prop.todo); +} +function TodoList({ todos }) { + return /*#__PURE__*/ React.createElement("div", null, .../*#__PURE__*/ React.createElement(Todo, { + key: todos[0].id, + todo: todos[0].todo + })); +} +function TodoListNoError({ todos }) { + // any is not checked + return /*#__PURE__*/ React.createElement("div", null, .../*#__PURE__*/ React.createElement(Todo, { + key: todos[0].id, + todo: todos[0].todo + })); +} +let x; +/*#__PURE__*/ React.createElement(TodoList, x); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react.2.minified.js new file mode 100644 index 000000000000..240e855a3c76 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es2015)_react.2.minified.js @@ -0,0 +1 @@ +//// [tsxSpreadChildrenInvalidType.tsx] diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).1.normal.js index 6709b62d73cb..4221585af210 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).1.normal.js @@ -1,28 +1,28 @@ //// [tsxSpreadChildrenInvalidType.tsx] +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array"; +import { jsx as _jsx } from "react/jsx-runtime"; function Todo(prop) { - return /*#__PURE__*/ React.createElement("div", null, prop.key.toString() + prop.todo); + return /*#__PURE__*/ _jsx("div", { + children: prop.key.toString() + prop.todo + }); } function TodoList(param) { var todos = param.todos; - return /*#__PURE__*/ React.createElement.apply(React, [ - "div", - null - ].concat(_to_consumable_array(/*#__PURE__*/ React.createElement(Todo, { - key: todos[0].id, - todo: todos[0].todo - })))); + return /*#__PURE__*/ _jsx("div", { + children: _to_consumable_array(/*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id)) + }); } function TodoListNoError(param) { var todos = param.todos; // any is not checked - return /*#__PURE__*/ React.createElement.apply(React, [ - "div", - null - ].concat(_to_consumable_array(/*#__PURE__*/ React.createElement(Todo, { - key: todos[0].id, - todo: todos[0].todo - })))); + return /*#__PURE__*/ _jsx("div", { + children: _to_consumable_array(/*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id)) + }); } var x; -/*#__PURE__*/ React.createElement(TodoList, x); +/*#__PURE__*/ _jsx(TodoList, _object_spread({}, x)); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).2.minified.js index 81cb1ca76daa..2de786947dbf 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5).2.minified.js @@ -1,2 +1,6 @@ //// [tsxSpreadChildrenInvalidType.tsx] +var x; +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; import "@swc/helpers/_/_to_consumable_array"; +import "react/jsx-runtime"; +_object_spread({}, x); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react-jsx.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react-jsx.1.normal.js new file mode 100644 index 000000000000..4221585af210 --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react-jsx.1.normal.js @@ -0,0 +1,28 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array"; +import { jsx as _jsx } from "react/jsx-runtime"; +function Todo(prop) { + return /*#__PURE__*/ _jsx("div", { + children: prop.key.toString() + prop.todo + }); +} +function TodoList(param) { + var todos = param.todos; + return /*#__PURE__*/ _jsx("div", { + children: _to_consumable_array(/*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id)) + }); +} +function TodoListNoError(param) { + var todos = param.todos; + // any is not checked + return /*#__PURE__*/ _jsx("div", { + children: _to_consumable_array(/*#__PURE__*/ _jsx(Todo, { + todo: todos[0].todo + }, todos[0].id)) + }); +} +var x; +/*#__PURE__*/ _jsx(TodoList, _object_spread({}, x)); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react-jsx.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react-jsx.2.minified.js new file mode 100644 index 000000000000..2de786947dbf --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react-jsx.2.minified.js @@ -0,0 +1,6 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +var x; +import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; +import "@swc/helpers/_/_to_consumable_array"; +import "react/jsx-runtime"; +_object_spread({}, x); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react.1.normal.js new file mode 100644 index 000000000000..6709b62d73cb --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react.1.normal.js @@ -0,0 +1,28 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array"; +function Todo(prop) { + return /*#__PURE__*/ React.createElement("div", null, prop.key.toString() + prop.todo); +} +function TodoList(param) { + var todos = param.todos; + return /*#__PURE__*/ React.createElement.apply(React, [ + "div", + null + ].concat(_to_consumable_array(/*#__PURE__*/ React.createElement(Todo, { + key: todos[0].id, + todo: todos[0].todo + })))); +} +function TodoListNoError(param) { + var todos = param.todos; + // any is not checked + return /*#__PURE__*/ React.createElement.apply(React, [ + "div", + null + ].concat(_to_consumable_array(/*#__PURE__*/ React.createElement(Todo, { + key: todos[0].id, + todo: todos[0].todo + })))); +} +var x; +/*#__PURE__*/ React.createElement(TodoList, x); diff --git a/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react.2.minified.js new file mode 100644 index 000000000000..81cb1ca76daa --- /dev/null +++ b/crates/swc/tests/tsc-references/tsxSpreadChildrenInvalidType(target=es5)_react.2.minified.js @@ -0,0 +1,2 @@ +//// [tsxSpreadChildrenInvalidType.tsx] +import "@swc/helpers/_/_to_consumable_array"; diff --git a/crates/swc/tests/tsc-references/tsxSpreadInvalidType.1.normal.js b/crates/swc/tests/tsc-references/tsxSpreadInvalidType.1.normal.js index 8fba88db4de3..93cbd7f98fb5 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadInvalidType.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxSpreadInvalidType.1.normal.js @@ -2,6 +2,6 @@ var a = {}; var b = null; var c = undefined; -var d = /*#__PURE__*/ React.createElement("div", a); -var e = /*#__PURE__*/ React.createElement("div", b); -var f = /*#__PURE__*/ React.createElement("div", c); +var d =
; +var e =
; +var f =
; diff --git a/crates/swc/tests/tsc-references/tsxSpreadInvalidType.2.minified.js b/crates/swc/tests/tsc-references/tsxSpreadInvalidType.2.minified.js index 2c48350f0eb8..a7f32d84a442 100644 --- a/crates/swc/tests/tsc-references/tsxSpreadInvalidType.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxSpreadInvalidType.2.minified.js @@ -1 +1,2 @@ //// [a.tsx] +
,
,
; diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.1.normal.js index 2918ec5372c9..4b25e00bb515 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.1.normal.js @@ -1,75 +1,25 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); // OK - var c1 = /*#__PURE__*/ _react.createElement(OneThing, { - yxx: "ok" - }); - var c2 = /*#__PURE__*/ _react.createElement(OneThing, { - yy: 100, - yy1: "hello" - }); - var c3 = /*#__PURE__*/ _react.createElement(OneThing, { - yxx: "hello", - "ignore-prop": true - }); - var c4 = /*#__PURE__*/ _react.createElement(OneThing, { - data: "hello", - "data-prop": true - }); - var c5 = /*#__PURE__*/ _react.createElement(OneThing, { - yxx1: "ok" - }, "Hello"); + var c1 = ; + var c2 = ; + var c3 = ; + var c4 = ; + var c5 = Hello; // OK - var d1 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - y1: true, - "extra-data": true - }); - var d2 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - "extra-data": "hello" - }); - var d3 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - "extra-data": "hello", - yy: "hihi" - }); - var d4 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - "extra-data": "hello", - yy: 9, - direction: 10 - }); - var d5 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - "extra-data": "hello", - yy: "hello", - name: "Bob" - }); + var d1 = ; + var d2 = ; + var d3 = ; + var d4 = ; + var d5 = ; // OK - var e1 = /*#__PURE__*/ _react.createElement(TestingOptional, null); - var e3 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: "hello" - }); - var e4 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: "hello", - y2: 1000 - }); - var e5 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: true, - y3: true - }); - var e6 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: true, - y3: true, - y2: 10 - }); - var e2 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: true, - y3: true, - "extra-prop": true - }); + var e1 = ; + var e3 = ; + var e4 = ; + var e5 = ; + var e6 = ; + var e2 = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.2.minified.js index f4b879bc672d..d4e9f2f8b349 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload1.2.minified.js @@ -1,10 +1,6 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }), OneThing, OneThing, OneThing, OneThing, OneThing, TestingOneThing, TestingOneThing, TestingOneThing, TestingOneThing, TestingOneThing, TestingOptional, TestingOptional, TestingOptional, TestingOptional, TestingOptional, TestingOptional; + "require" +], function(require) { + , , , , Hello, , , , , , , , , , , ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.1.normal.js index a2cbc1de209c..cea6be29cab1 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.1.normal.js @@ -1,15 +1,8 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var obj = { yy: 10, yy1: "hello" @@ -23,28 +16,21 @@ define([ }; var defaultObj; // OK - var c1 = /*#__PURE__*/ _react.createElement(OneThing, null); - var c2 = /*#__PURE__*/ _react.createElement(OneThing, obj); - var c3 = /*#__PURE__*/ _react.createElement(OneThing, {}); - var c4 = /*#__PURE__*/ _react.createElement(OneThing, _object_spread._({}, obj1, obj)); - var c5 = /*#__PURE__*/ _react.createElement(OneThing, _object_spread_props._(_object_spread._({}, obj1), { - yy: 42, + var c1 = ; + var c2 = ; + var c3 = ; + var c4 = ; + var c5 = ; + var c6 = ; + var c7 = ; // No error. should pick second overload + var c8 = ; + var c9 = ; + var c10 = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.2.minified.js index e98ba89f17ea..a269529f7d0b 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload2.2.minified.js @@ -1,32 +1,22 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { var defaultObj, obj = { yy: 10, yy1: "hello" }, obj1 = { yy: !0 }; - OneThing, OneThing, OneThing, OneThing, _object_spread._({}, obj1, obj), OneThing, _object_spread_props._(_object_spread._({}, obj1), { - yy: 42, + , , , , , , , , , ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.1.normal.js index ffde326ed18f..34983b65817d 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.1.normal.js @@ -1,37 +1,17 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props" -], function(require, exports, _object_spread, _object_spread_props) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var obj2; // OK - var two1 = /*#__PURE__*/ React.createElement(ZeroThingOrTwoThing, null); - var two2 = /*#__PURE__*/ React.createElement(ZeroThingOrTwoThing, { - yy: 100, - yy1: "hello" - }); - var two3 = /*#__PURE__*/ React.createElement(ZeroThingOrTwoThing, obj2); // it is just any so we allow it to pass through - var two4 = /*#__PURE__*/ React.createElement(ZeroThingOrTwoThing, _object_spread._({ - yy: 1000 - }, obj2)); // it is just any so we allow it to pass through - var two5 = /*#__PURE__*/ React.createElement(ZeroThingOrTwoThing, _object_spread_props._(_object_spread._({}, obj2), { - yy: 1000 - })); // it is just any so we allow it to pass through + var two1 = ; + var two2 = ; + var two3 = ; // it is just any so we allow it to pass through + var two4 = ; // it is just any so we allow it to pass through + var two5 = ; // it is just any so we allow it to pass through // OK - var three1 = /*#__PURE__*/ React.createElement(ThreeThing, { - yy: 99, - yy1: "hello world" - }); - var three2 = /*#__PURE__*/ React.createElement(ThreeThing, { - y2: "Bye" - }); - var three3 = /*#__PURE__*/ React.createElement(ThreeThing, _object_spread_props._(_object_spread._({}, obj2), { - y2: 10 - })); // it is just any so we allow it to pass through + var three1 = ; + var three2 = ; + var three3 = ; // it is just any so we allow it to pass through }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.2.minified.js index 95d827e8602c..d6f6f703d533 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload3.2.minified.js @@ -1,18 +1,7 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props" -], function(require, exports, _object_spread, _object_spread_props) { + "require" +], function(require) { var obj2; - Object.defineProperty(exports, "__esModule", { - value: !0 - }), ZeroThingOrTwoThing, ZeroThingOrTwoThing, ZeroThingOrTwoThing, ZeroThingOrTwoThing, _object_spread._({ - yy: 1000 - }, obj2), ZeroThingOrTwoThing, _object_spread_props._(_object_spread._({}, obj2), { - yy: 1000 - }), ThreeThing, ThreeThing, ThreeThing, _object_spread_props._(_object_spread._({}, obj2), { - y2: 10 - }); + , , , , , , , ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.1.normal.js index 525140090a5e..9468e7661e97 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.1.normal.js @@ -1,70 +1,34 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var obj = { yy: 10, yy1: "hello" }; var obj2; // Error - var c0 = /*#__PURE__*/ _react.createElement(OneThing, { - extraProp: true - }); // extra property; - var c1 = /*#__PURE__*/ _react.createElement(OneThing, { - yy: 10 - }); // missing property; - var c2 = /*#__PURE__*/ _react.createElement(OneThing, _object_spread_props._(_object_spread._({}, obj), { - yy1: true - })); // type incompatible; - var c3 = /*#__PURE__*/ _react.createElement(OneThing, _object_spread_props._(_object_spread._({}, obj), { + var c0 = ; // extra property; + var c1 = ; // missing property; + var c2 = ; // type incompatible; + var c3 = ; // This is OK because all attribute are spread + var c4 = ; // extra property; + var c5 = ; // type incompatible; + var c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not + var c7 = ; // Should error as there is extra attribute that doesn't match any. Current it is not // Error - var d1 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - "extra-data": true - }); - var d2 = /*#__PURE__*/ _react.createElement(TestingOneThing, { - yy: "hello", - direction: "left" - }); + var d1 = ; + var d2 = ; // Error - var e1 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: true, - y3: "hello" - }); - var e2 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: "hello", - y2: 1000, - y3: true - }); - var e3 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: "hello", - y2: 1000, - children: "hi" - }); - var e4 = /*#__PURE__*/ _react.createElement(TestingOptional, { - y1: "hello", - y2: 1000 - }, "Hi"); + var e1 = ; + var e2 = ; + var e3 = ; + var e4 = Hi; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.2.minified.js index 4de4c0619a1b..85e15472cf6e 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload4.2.minified.js @@ -1,29 +1,16 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { var obj2, obj = { yy: 10, yy1: "hello" }; - OneThing, OneThing, OneThing, _object_spread_props._(_object_spread._({}, obj), { - yy1: !0 - }), OneThing, _object_spread_props._(_object_spread._({}, obj), { + , , , , , , , , , , , , , Hi; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.1.normal.js index 8913a8d31574..9ce65216e16b 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.1.normal.js @@ -1,11 +1,8 @@ //// [file.tsx] define([ "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "exports" +], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true @@ -35,36 +32,25 @@ define([ return this._buildMainButton(props); } // Error - var b0 = /*#__PURE__*/ _react.createElement(MainButton, { - to: "/some/path", - onClick: function(e) {} - }, "GO"); // extra property; - var b1 = /*#__PURE__*/ _react.createElement(MainButton, _object_spread._({ - onClick: function(e) {} - }, obj0), "Hello world"); // extra property; - var b2 = /*#__PURE__*/ _react.createElement(MainButton, _object_spread._({ + var b0 = GO; // extra property; + var b1 = Hello world; // extra property; + var b2 = ; // extra property + var b3 = ; // extra property + var b4 = ; // Should error because Incorrect type; but attributes are any so everything is allowed + var b5 = ; // Spread retain method declaration (see GitHub #13365), so now there is an extra attributes + var b6 = ; // incorrect type for optional attribute + var b7 = ; // incorrect type for optional attribute + var b8 = ; // incorrect type for specified hyphanated name }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.2.minified.js index 6aaad2575af8..0c62f85d5234 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload5.2.minified.js @@ -1,11 +1,8 @@ //// [file.tsx] define([ "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "exports" +], function(require, exports) { Object.defineProperty(exports, "__esModule", { value: !0 }), Object.defineProperty(exports, "MainButton", { @@ -20,15 +17,19 @@ define([ function MainButton(props) { return props.to ? this._buildMainLink(props) : this._buildMainButton(props); } - _object_spread._({ - onClick: function(e) {} - }, obj0), _object_spread._({ + GO, Hello world, , , , , , , ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.1.normal.js index 9098f8ee45fc..b6e6f90e93e1 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.1.normal.js @@ -1,11 +1,8 @@ //// [file.tsx] define([ "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "exports" +], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true @@ -32,43 +29,25 @@ define([ return this._buildMainButton(props); } // OK - var b0 = /*#__PURE__*/ _react.createElement(MainButton, { - to: "/some/path" - }, "GO"); - var b1 = /*#__PURE__*/ _react.createElement(MainButton, { - onClick: function(e) {} - }, "Hello world"); - var b2 = /*#__PURE__*/ _react.createElement(MainButton, obj); - var b3 = /*#__PURE__*/ _react.createElement(MainButton, _object_spread._({ + var b0 = GO; + var b1 = Hello world; + var b2 = ; + var b3 = ; + var b4 = ; // any; just pick the first overload + var b5 = ; // should pick the second overload + var b6 = ; + var b7 = ; + var b8 = ; // OK; method declaration get retained (See GitHub #13365) + var b9 = GO; + var b10 = ; + var b11 = Hello world; + var b12 = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.2.minified.js index 2b5f421fb29f..df43a6c5b913 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentOverload6.2.minified.js @@ -1,15 +1,8 @@ //// [file.tsx] define([ "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - var obj1; - function MainButton(props) { - return props.to ? this._buildMainLink(props) : this._buildMainButton(props); - } + "exports" +], function(require, exports) { Object.defineProperty(exports, "__esModule", { value: !0 }), Object.defineProperty(exports, "MainButton", { @@ -17,12 +10,23 @@ define([ get: function() { return MainButton; } - }), _object_spread._({ - to: 10000 - }, { + }); + var obj1, obj = { children: "hi", to: "boo" - }), _object_spread_props._(_object_spread._({}, obj1), { - to: "/to/somewhere" - }); + }; + function MainButton(props) { + return props.to ? this._buildMainLink(props) : this._buildMainButton(props); + } + GO, Hello world, , , , , , , , GO, , Hello world, ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.1.normal.js index 07ba1431f105..45616bf167a2 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.1.normal.js @@ -1,21 +1,12 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); function MyComponent(attr) { - return /*#__PURE__*/ _react.createElement("div", null, "attr.values"); + return
attr.values
; } // OK - var i = /*#__PURE__*/ _react.createElement(MyComponent, { - values: true - }); // We infer type arguments here - var i1 = /*#__PURE__*/ _react.createElement(MyComponent, { - values: "Hello" - }); + var i = ; // We infer type arguments here + var i1 = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.2.minified.js index 7657cb32d106..6c2999549ec8 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter1.2.minified.js @@ -1,10 +1,9 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { + function MyComponent(attr) { + return
attr.values
; + } + , ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.1.normal.js index 4e48af305c79..7eee4a4cb0ff 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.1.normal.js @@ -1,18 +1,11 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); function MyComponent1(attr) { - return /*#__PURE__*/ _react.createElement("div", null, "attr.values"); + return
attr.values
; } // Error - var i1 = /*#__PURE__*/ _react.createElement(MyComponent1, { - values: 5 - }); + var i1 = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.2.minified.js index 7657cb32d106..81de75cf526a 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentWithDefaultTypeParameter2.2.minified.js @@ -1,10 +1,9 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { + function MyComponent1(attr) { + return
attr.values
; + } + ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.1.normal.js index fba1e53f10e6..8752b4d33a0e 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.1.normal.js @@ -1,24 +1,23 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); var Foo = function(props) { - return /*#__PURE__*/ _react.createElement("div", null); + return
; }; // Should be OK - var foo = /*#__PURE__*/ _react.createElement(Foo, null); + var foo = ; // Should be OK var MainMenu = function(props) { - return /*#__PURE__*/ _react.createElement("div", null, /*#__PURE__*/ _react.createElement("h3", null, "Main Menu")); + return
+

Main Menu

+
; }; var App = function(param) { var children = param.children; - return /*#__PURE__*/ _react.createElement("div", null, /*#__PURE__*/ _react.createElement(MainMenu, null)); + return
+ +
; }; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.2.minified.js index 7657cb32d106..ecb7a7573d19 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponents3.2.minified.js @@ -1,10 +1,9 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); + "require" +], function(require) { + var Foo = function(props) { + return
; + }; + ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.1.normal.js index 822af1eea2c5..af0581272627 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.1.normal.js @@ -1,44 +1,28 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); // OK function Baz(key1, value) { - var a0 = /*#__PURE__*/ _react.createElement(ComponentWithTwoAttributes, { + var a0 = ; + var a1 = ; } // OK function createLink(func) { - var o = /*#__PURE__*/ _react.createElement(Link, { - func: func - }); + var o = ; } function createLink1(func) { - var o = /*#__PURE__*/ _react.createElement(Link, { - func: func - }); + var o = ; } // OK - var i = /*#__PURE__*/ _react.createElement(InferParamComponent, { - values: [ - 1, - 2, - 3, - 4 - ], - selectHandler: function(val) {} - }); + var i = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.2.minified.js index 9e3034872c3d..0d31ed7507d0 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments1.2.minified.js @@ -1,10 +1,11 @@ //// [file.tsx] define([ - "require", - "exports", - "react" -], function(require, exports, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }), InferParamComponent; + "require" +], function(require) { + ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.1.normal.js index 40f38b1be59f..8b58e4c0bd2d 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.1.normal.js @@ -1,39 +1,25 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); // Error function Bar(arg) { - var a1 = /*#__PURE__*/ _react.createElement(ComponentSpecific1, _object_spread_props._(_object_spread._({}, arg), { - "ignore-prop": 10 - })); + var a1 = ; } // Error function Baz(arg) { - var a0 = /*#__PURE__*/ _react.createElement(ComponentSpecific1, arg); + var a0 = ; } // Error function createLink(func) { - var o = /*#__PURE__*/ _react.createElement(Link, { - func: func - }); + var o = ; } // Error - var i = /*#__PURE__*/ _react.createElement(InferParamComponent, { - values: [ - 1, - 2, - 3, - 4 - ], - selectHandler: function(val) {} - }); + var i = ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.2.minified.js index 0caadeb2feab..0d31ed7507d0 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments2.2.minified.js @@ -1,12 +1,11 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }), InferParamComponent; + "require" +], function(require) { + ; }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.1.normal.js index 369da7845a2f..9916beab3ac3 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.1.normal.js @@ -1,42 +1,20 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); // OK function Baz(arg1, arg2) { - var a0 = /*#__PURE__*/ _react.createElement(OverloadComponent, _object_spread_props._(_object_spread._({}, arg1), { - a: "hello", - "ignore-prop": true - })); - var a1 = /*#__PURE__*/ _react.createElement(OverloadComponent, _object_spread_props._(_object_spread._({}, arg2), { - "ignore-pro": "hello world" - })); - var a2 = /*#__PURE__*/ _react.createElement(OverloadComponent, arg2); - var a3 = /*#__PURE__*/ _react.createElement(OverloadComponent, _object_spread_props._(_object_spread._({}, arg1), { - "ignore-prop": true - })); - var a4 = /*#__PURE__*/ _react.createElement(OverloadComponent, null); - var a5 = /*#__PURE__*/ _react.createElement(OverloadComponent, _object_spread._(_object_spread_props._(_object_spread._({}, arg2), { - "ignore-prop": "hello" - }), arg1)); - var a6 = /*#__PURE__*/ _react.createElement(OverloadComponent, _object_spread._(_object_spread_props._(_object_spread._({}, arg2), { - "ignore-prop": true - }), arg1)); + var a0 = ; + var a1 = ; + var a2 = ; + var a3 = ; + var a4 = ; + var a5 = ; + var a6 = ; } function createLink(func) { - var o = /*#__PURE__*/ _react.createElement(Link, { - func: func - }); - var o1 = /*#__PURE__*/ _react.createElement(Link, { - func: function(a, b) {} - }); + var o = ; + var o1 = ; } }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.2.minified.js index 1af4b0e0572b..344d24dc328e 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments3.2.minified.js @@ -1,12 +1,4 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); -}); + "require" +], function(require) {}); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.1.normal.js index b03d9cdf9563..36d24051a272 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.1.normal.js @@ -1,23 +1,12 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); // Error function Baz(arg1, arg2) { - var a0 = /*#__PURE__*/ _react.createElement(OverloadComponent, { - a: arg1.b - }); - var a2 = /*#__PURE__*/ _react.createElement(OverloadComponent, _object_spread_props._(_object_spread._({}, arg1), { - "ignore-prop": true - })); + var a0 = ; + var a2 = ; // missing a } }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.2.minified.js index 1af4b0e0572b..344d24dc328e 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments4.2.minified.js @@ -1,12 +1,4 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); -}); + "require" +], function(require) {}); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.1.normal.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.1.normal.js index 772ea6caf52e..7abe33e74265 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.1.normal.js @@ -1,33 +1,16 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { + "require" +], function(require) { "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); function createComponent(arg) { - var a1 = /*#__PURE__*/ _react.createElement(Component, arg); - var a2 = /*#__PURE__*/ _react.createElement(Component, _object_spread_props._(_object_spread._({}, arg), { - prop1: true - })); + var a1 = ; + var a2 = ; } function Bar(arg) { - var a1 = /*#__PURE__*/ _react.createElement(ComponentSpecific, _object_spread_props._(_object_spread._({}, arg), { - "ignore-prop": "hi" - })); // U is number - var a2 = /*#__PURE__*/ _react.createElement(ComponentSpecific1, _object_spread_props._(_object_spread._({}, arg), { - "ignore-prop": 10 - })); // U is number - var a3 = /*#__PURE__*/ _react.createElement(ComponentSpecific, _object_spread_props._(_object_spread._({}, arg), { - prop: "hello" - })); // U is "hello" - var a4 = /*#__PURE__*/ _react.createElement(ComponentSpecific, _object_spread_props._(_object_spread._({}, arg), { - prop1: "hello" - })); // U is "hello" + var a1 = ; // U is number + var a2 = ; // U is number + var a3 = ; // U is "hello" + var a4 = ; // U is "hello" } }); diff --git a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.2.minified.js b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.2.minified.js index 1af4b0e0572b..344d24dc328e 100644 --- a/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxStatelessFunctionComponentsWithTypeArguments5.2.minified.js @@ -1,12 +1,4 @@ //// [file.tsx] define([ - "require", - "exports", - "@swc/helpers/_/_object_spread", - "@swc/helpers/_/_object_spread_props", - "react" -], function(require, exports, _object_spread, _object_spread_props, _react) { - Object.defineProperty(exports, "__esModule", { - value: !0 - }); -}); + "require" +], function(require) {}); diff --git a/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.1.normal.js b/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.1.normal.js index dcce41984a02..2ce52a961d6e 100644 --- a/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.1.normal.js @@ -1,10 +1,29 @@ //// [foo.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | type TypeProps = { foo?: boolean; }; -//! 5 | interface InterfaceProps { foo?: boolean; } -//! `---- +function Foo() { + return null; +} +<> + { /* JsxSelfClosingElement */ } + + + + + + + + + + + + { /* JsxOpeningElement */ } + + + + + + + + + + +; diff --git a/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.2.minified.js b/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.2.minified.js index dcce41984a02..a8abf704759d 100644 --- a/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxTypeArgumentsJsxPreserveOutput.2.minified.js @@ -1,10 +1,29 @@ //// [foo.tsx] -//! x Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead. -//! ,-[2:1] -//! 1 | -//! 2 | import React = require('react'); -//! : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -//! 3 | -//! 4 | type TypeProps = { foo?: boolean; }; -//! 5 | interface InterfaceProps { foo?: boolean; } -//! `---- +function Foo() { + return null; +} +<> + {} + + + + + + + + + + + + {} + + + + + + + + + + +; diff --git a/crates/swc/tests/tsc-references/tsxTypeErrors.1.normal.js b/crates/swc/tests/tsc-references/tsxTypeErrors.1.normal.js index 83b096809626..1c9b1087e94e 100644 --- a/crates/swc/tests/tsc-references/tsxTypeErrors.1.normal.js +++ b/crates/swc/tests/tsc-references/tsxTypeErrors.1.normal.js @@ -1,24 +1,16 @@ //// [tsxTypeErrors.tsx] // A built-in element (OK) import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; -var a1 = /*#__PURE__*/ React.createElement("div", { - id: "foo" -}); +var a1 =
; // A built-in element with a mistyped property (error) -var a2 = /*#__PURE__*/ React.createElement("img", { - srce: "foo.jpg" -}); +var a2 = ; // A built-in element with a badly-typed attribute value (error) var thing = { oops: 100 }; -var a3 = /*#__PURE__*/ React.createElement("div", { - id: thing -}); +var a3 =
; // Mistyped html name (error) -var e1 = /*#__PURE__*/ React.createElement("imag", { - src: "bar.jpg" -}); +var e1 = ; // A custom type var MyClass = function MyClass() { "use strict"; @@ -26,16 +18,12 @@ var MyClass = function MyClass() { }; // Let's use it // TODO: Error on missing 'reqd' -var b1 = /*#__PURE__*/ React.createElement(MyClass, { - reqd: true -}); +var b1 = ; // Mistyped attribute member // sample.tsx(23,22): error TS2322: Type '{ x: number; y: string; }' is not assignable to type '{ x: number; y: number; }'. // Types of property 'y' are incompatible. // Type 'string' is not assignable to type 'number'. -var b2 = /*#__PURE__*/ React.createElement(MyClass, { - pt: { - x: 4, - y: 'oops' - } -}); +var b2 = ; diff --git a/crates/swc/tests/tsc-references/tsxTypeErrors.2.minified.js b/crates/swc/tests/tsc-references/tsxTypeErrors.2.minified.js index 641f797ac227..8fdfcc0e07c7 100644 --- a/crates/swc/tests/tsc-references/tsxTypeErrors.2.minified.js +++ b/crates/swc/tests/tsc-references/tsxTypeErrors.2.minified.js @@ -1,2 +1,12 @@ //// [tsxTypeErrors.tsx] -import "@swc/helpers/_/_class_call_check"; +import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; +
, ,
, ; +var MyClass = function MyClass() { + _class_call_check(this, MyClass); +}; +, ; diff --git a/crates/swc/tests/tsc.rs b/crates/swc/tests/tsc.rs index e324bd796587..742520896f41 100644 --- a/crates/swc/tests/tsc.rs +++ b/crates/swc/tests/tsc.rs @@ -23,6 +23,7 @@ use swc::{ use swc_common::{errors::ColorConfig, FileName, SourceFile, SourceMap, GLOBALS}; use swc_ecma_ast::EsVersion; use swc_ecma_parser::{Syntax, TsSyntax}; +use swc_ecma_transforms::react; use testing::NormalizedOutput; #[testing::fixture( @@ -106,6 +107,7 @@ fn matrix(input: &Path) -> Vec { let mut decorator_metadata = false; let mut use_define_for_class_fields = false; let mut verbatim_module_syntax = false; + let mut react = vec![]; let filename = input .file_name() @@ -131,7 +133,21 @@ fn matrix(input: &Path) -> Vec { "target" => { targets.extend(target(&meta_data_value.to_lowercase())); } - "jsx" => {} + "jsx" => { + // react-jsx,react-jsxdev + // split by comma and trim each value + let values: Vec<_> = meta_data_value + .split(',') + .map(|v| v.trim().to_lowercase()) + .collect(); + + for value in values { + let Ok(options) = react::Options::try_from(value.as_str()) else { + continue; + }; + react.push(options); + } + } "removecomments" => {} "importhelpers" => {} "downleveliteration" => {} @@ -353,73 +369,82 @@ fn matrix(input: &Path) -> Vec { let base_name = input.with_extension(""); let base_name = base_name.file_name().map(OsStr::to_string_lossy).unwrap(); - for minify in [None, Some(default_minify)] { - for target in targets.clone() { - for module in modules.clone() { - let mut vary_name = Vec::new(); + let react_len = react.len(); + for react in react { + for minify in [None, Some(&default_minify)] { + for target in targets.clone() { + for module in modules.clone() { + let mut vary_name = Vec::new(); - if modules.len() > 1 { - vary_name.push(format!("module={}", &module)); - } + if modules.len() > 1 { + vary_name.push(format!("module={}", &module)); + } - if targets.len() > 1 { - vary_name.push(format!( - "target={}", - serde_json::to_string(&target).unwrap().replace('"', "") - )); - } + if targets.len() > 1 { + vary_name.push(format!( + "target={}", + serde_json::to_string(&target).unwrap().replace('"', "") + )); + } - let mut filename = base_name.to_string(); - if !vary_name.is_empty() { - filename.push('('); - filename.push_str(&vary_name.join(",")); - filename.push(')'); - } + let mut filename = base_name.to_string(); + if !vary_name.is_empty() { + filename.push('('); + filename.push_str(&vary_name.join(",")); + filename.push(')'); + } - if minify.is_some() { - filename.push_str(".2.minified.js"); - } else { - filename.push_str(".1.normal.js"); - } + if react_len > 1 { + filename.push('_'); + filename.push_str(&react_options_to_file_name(&react)); + } - let opts = Options { - config: Config { - jsc: JscConfig { - syntax: Some(Syntax::Typescript(TsSyntax { - tsx: is_jsx, - decorators, - dts: false, - no_early_errors: false, - disallow_ambiguous_jsx_like: false, - })), - external_helpers: true.into(), - target: Some(target), - minify: minify.clone(), - transform: Some(TransformConfig { - use_define_for_class_fields: use_define_for_class_fields.into(), - decorator_metadata: decorator_metadata.into(), - verbatim_module_syntax: verbatim_module_syntax.into(), - ..Default::default() - }) - .into(), - experimental: JscExperimental { - disable_all_lints: false.into(), + if minify.is_some() { + filename.push_str(".2.minified.js"); + } else { + filename.push_str(".1.normal.js"); + } + + let opts = Options { + config: Config { + jsc: JscConfig { + syntax: Some(Syntax::Typescript(TsSyntax { + tsx: is_jsx, + decorators, + dts: false, + no_early_errors: false, + disallow_ambiguous_jsx_like: false, + })), + external_helpers: true.into(), + target: Some(target), + minify: minify.cloned(), + transform: Some(TransformConfig { + use_define_for_class_fields: use_define_for_class_fields.into(), + decorator_metadata: decorator_metadata.into(), + verbatim_module_syntax: verbatim_module_syntax.into(), + react: react.clone(), + ..Default::default() + }) + .into(), + experimental: JscExperimental { + disable_all_lints: false.into(), + ..Default::default() + }, ..Default::default() }, + module: Some(module.into()), ..Default::default() }, - module: Some(module.into()), ..Default::default() - }, - ..Default::default() - }; - - test_unit_data_list.push(TestUnitData { - cm: cm.clone(), - files: files.clone(), - opts, - output: filename, - }) + }; + + test_unit_data_list.push(TestUnitData { + cm: cm.clone(), + files: files.clone(), + opts, + output: filename, + }) + } } } } @@ -469,3 +494,19 @@ fn compile(output: &Path, test_unit_data: TestUnitData) { .compare_to_file(output) .unwrap(); } + +fn react_options_to_file_name(options: &react::Options) -> String { + let mut name = String::new(); + + match options.runtime { + react::Runtime::Automatic(_) => name.push_str("react-jsx"), + react::Runtime::Classic(_) => name.push_str("react"), + react::Runtime::Preserve => name.push_str("preserve"), + } + + if options.common.development.into_bool() { + name.push_str("-dev"); + } + + name +} diff --git a/crates/swc/tests/vercel/full/react-autowhatever/1/output/index.js b/crates/swc/tests/vercel/full/react-autowhatever/1/output/index.js index 83049ad6a68f..c154b1e944cb 100644 --- a/crates/swc/tests/vercel/full/react-autowhatever/1/output/index.js +++ b/crates/swc/tests/vercel/full/react-autowhatever/1/output/index.js @@ -7,15 +7,15 @@ Object.defineProperty(exports, "__esModule", { return o; } }); -var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_class_call_check"), r = require("@swc/helpers/_/_create_class"), i = require("@swc/helpers/_/_define_property"), n = require("@swc/helpers/_/_inherits"), s = require("@swc/helpers/_/_interop_require_default"), u = require("@swc/helpers/_/_interop_require_wildcard"), d = require("@swc/helpers/_/_object_spread"), c = require("@swc/helpers/_/_object_spread_props"), l = require("react/jsx-runtime"), _ = /*#__PURE__*/ u._(require("react")), a = /*#__PURE__*/ s._(require("prop-types")), o = /*#__PURE__*/ function(s) { +var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_class_call_check"), r = require("@swc/helpers/_/_create_class"), i = require("@swc/helpers/_/_define_property"), n = require("@swc/helpers/_/_inherits"), s = require("@swc/helpers/_/_interop_require_default"), u = require("@swc/helpers/_/_object_spread"), d = require("@swc/helpers/_/_object_spread_props"), c = require("react/jsx-runtime"), l = require("react"), a = /*#__PURE__*/ s._(require("prop-types")), o = /*#__PURE__*/ function(s) { "use strict"; - function u() { + function l() { var r; - return t._(this, u), r = e._(this, u, arguments), i._(r, "storeHighlightedItemReference", function(e) { + return t._(this, l), r = e._(this, l, arguments), i._(r, "storeHighlightedItemReference", function(e) { r.props.onHighlightedItemChange(null === e ? null : e.item); }), r; } - return n._(u, s), r._(u, [ + return n._(l, s), r._(l, [ { key: "shouldComponentUpdate", value: function(e) { @@ -25,20 +25,20 @@ var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_clas { key: "render", value: function() { - var e = this, t = this.props, r = t.items, i = t.itemProps, n = t.renderItem, s = t.renderItemData, u = t.sectionIndex, _ = t.highlightedItemIndex, a = t.getItemId, o = t.theme, p = t.keyPrefix, h = null === u ? p : "".concat(p, "section-").concat(u, "-"), f = "function" == typeof i; - return (0, l.jsx)("ul", c._(d._({ + var e = this, t = this.props, r = t.items, i = t.itemProps, n = t.renderItem, s = t.renderItemData, l = t.sectionIndex, a = t.highlightedItemIndex, o = t.getItemId, _ = t.theme, p = t.keyPrefix, f = null === l ? p : "".concat(p, "section-").concat(l, "-"), h = "function" == typeof i; + return (0, c.jsx)("ul", d._(u._({ role: "listbox" - }, o("".concat(h, "items-list"), "itemsList")), { + }, _("".concat(f, "items-list"), "itemsList")), { children: r.map(function(t, r) { - var p = 0 === r, m = r === _, I = "".concat(h, "item-").concat(r), g = f ? i({ - sectionIndex: u, + var p = 0 === r, m = r === a, I = "".concat(f, "item-").concat(r), g = h ? i({ + sectionIndex: l, itemIndex: r - }) : i, q = d._({ - id: a(u, r), + }) : i, q = u._({ + id: o(l, r), "aria-selected": m - }, o(I, "item", p && "itemFirst", m && "itemHighlighted"), g); - return m && (q.ref = e.storeHighlightedItemReference), (0, l.jsx)(Item, c._(d._({}, q), { - sectionIndex: u, + }, _(I, "item", p && "itemFirst", m && "itemHighlighted"), g); + return m && (q.ref = e.storeHighlightedItemReference), (0, c.jsx)(Item, d._(u._({}, q), { + sectionIndex: l, isHighlighted: m, itemIndex: r, item: t, @@ -49,8 +49,8 @@ var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_clas })); } } - ]), u; -}(_.Component); + ]), l; +}(l.Component); i._(o, "propTypes", { items: a.default.array.isRequired, itemProps: a.default.oneOfType([ diff --git a/crates/swc/tests/vercel/full/react-autowhatever/2/output/index.js b/crates/swc/tests/vercel/full/react-autowhatever/2/output/index.js index d4006d71c4d7..53533dd1d309 100644 --- a/crates/swc/tests/vercel/full/react-autowhatever/2/output/index.js +++ b/crates/swc/tests/vercel/full/react-autowhatever/2/output/index.js @@ -7,15 +7,15 @@ Object.defineProperty(exports, "__esModule", { return l; } }); -var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_class_call_check"), r = require("@swc/helpers/_/_create_class"), i = require("@swc/helpers/_/_define_property"), s = require("@swc/helpers/_/_inherits"), n = require("@swc/helpers/_/_interop_require_wildcard"), c = require("@swc/helpers/_/_object_spread"), _ = require("@swc/helpers/_/_object_spread_props"), o = require("react/jsx-runtime"), l = /*#__PURE__*/ function(n) { +var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_class_call_check"), r = require("@swc/helpers/_/_create_class"), i = require("@swc/helpers/_/_define_property"), n = require("@swc/helpers/_/_inherits"), s = require("@swc/helpers/_/_object_spread"), c = require("@swc/helpers/_/_object_spread_props"), o = require("react/jsx-runtime"), l = /*#__PURE__*/ function(l) { "use strict"; - function l() { + function u() { var r; - return t._(this, l), r = e._(this, l, arguments), i._(r, "storeHighlightedItemReference", function(e) { + return t._(this, u), r = e._(this, u, arguments), i._(r, "storeHighlightedItemReference", function(e) { r.props.onHighlightedItemChange(null === e ? null : e.item); }), r; } - return s._(l, n), r._(l, [ + return n._(u, l), r._(u, [ { key: "shouldComponentUpdate", value: function(e) { @@ -27,32 +27,32 @@ var e = require("@swc/helpers/_/_call_super"), t = require("@swc/helpers/_/_clas { key: "render", value: function() { - var e = this, t = this.props, r = t.items, i = t.itemProps, s = t.renderItem, n = t.renderItemData, l = t.sectionIndex, u = t.highlightedItemIndex, p = t.getItemId, a = t.theme, d = t.keyPrefix, h = null === l ? d : "".concat(d, "section-").concat(l, "-"), m = "function" == typeof i; - return (0, o.jsx)("ul", _._(c._({ + var e = this, t = this.props, r = t.items, i = t.itemProps, n = t.renderItem, l = t.renderItemData, u = t.sectionIndex, _ = t.highlightedItemIndex, p = t.getItemId, a = t.theme, d = t.keyPrefix, h = null === u ? d : "".concat(d, "section-").concat(u, "-"), m = "function" == typeof i; + return (0, o.jsx)("ul", c._(s._({ role: "listbox" }, a("".concat(h, "items-list"), "itemsList")), { children: r.map(function(t, r) { - var d = 0 === r, f = r === u, I = "".concat(h, "item-").concat(r), g = m ? i({ - sectionIndex: l, + var d = 0 === r, f = r === _, I = "".concat(h, "item-").concat(r), g = m ? i({ + sectionIndex: u, itemIndex: r - }) : i, x = c._({ - id: p(l, r), + }) : i, x = s._({ + id: p(u, r), "aria-selected": f }, a(I, "item", d && "itemFirst", f && "itemHighlighted"), g); - return f && (x.ref = e.storeHighlightedItemReference), (0, o.jsx)(Item, _._(c._({}, x), { - sectionIndex: l, + return f && (x.ref = e.storeHighlightedItemReference), (0, o.jsx)(Item, c._(s._({}, x), { + sectionIndex: u, isHighlighted: f, itemIndex: r, item: t, - renderItem: s, - renderItemData: n + renderItem: n, + renderItemData: l })); }) })); } } - ]), l; -}(/*#__PURE__*/ n._(require("react")).Component); + ]), u; +}(require("react").Component); i._(l, "propTypes", { items: 500 }), i._(l, "defaultProps", { diff --git a/crates/swc/tests/vercel/full/react-hooks/1/output/index.js b/crates/swc/tests/vercel/full/react-hooks/1/output/index.js index 3dbb520a210e..255f3a8a2204 100644 --- a/crates/swc/tests/vercel/full/react-hooks/1/output/index.js +++ b/crates/swc/tests/vercel/full/react-hooks/1/output/index.js @@ -1,5 +1,4 @@ import { jsx as r, Fragment as t } from "react/jsx-runtime"; -import "react"; import { useRouter as e } from "next/router"; import { useProject as o } from "@swr/use-project"; import a from "@swr/use-team"; diff --git a/crates/swc/tests/vercel/loader-only/2/output/index.js b/crates/swc/tests/vercel/loader-only/2/output/index.js index 8805cc89e04c..f1a2c60cc410 100644 --- a/crates/swc/tests/vercel/loader-only/2/output/index.js +++ b/crates/swc/tests/vercel/loader-only/2/output/index.js @@ -1,5 +1,4 @@ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; -import React from "react"; import { useRouter } from "next/router"; import { useProject } from "@swr/use-project"; import useTeam from "@swr/use-team"; diff --git a/crates/swc/tests/vercel/loader-only/react-autowhatever/1/output/index.js b/crates/swc/tests/vercel/loader-only/react-autowhatever/1/output/index.js index e1c17c5fb882..1aa2a00f52ca 100644 --- a/crates/swc/tests/vercel/loader-only/react-autowhatever/1/output/index.js +++ b/crates/swc/tests/vercel/loader-only/react-autowhatever/1/output/index.js @@ -6,7 +6,7 @@ import { _ as _inherits } from "@swc/helpers/_/_inherits"; import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; import { jsx as _jsx } from "react/jsx-runtime"; -import React, { Component } from "react"; +import { Component } from "react"; import PropTypes from "prop-types"; import Item from "./Item"; import compareObjects from "./compareObjects"; diff --git a/crates/swc_common/src/comments.rs b/crates/swc_common/src/comments.rs index 762bfa633c01..e1b31c77396e 100644 --- a/crates/swc_common/src/comments.rs +++ b/crates/swc_common/src/comments.rs @@ -45,6 +45,44 @@ pub trait Comments { fn add_pure_comment(&self, pos: BytePos); + /// Applies a closure to each comment without allocation. + /// + /// **⚠️ Iteration Order**: The order in which comments are visited is + /// **unspecified** and may vary between implementations and calls. Do + /// not rely on any particular order. + /// + /// This method is similar to `Iterator::for_each` but avoids the overhead + /// of creating an iterator object and intermediate collections. + /// + /// # Example + /// + /// ```rust + /// # use swc_common::comments::{SingleThreadedComments, Comments}; + /// let comments = SingleThreadedComments::default(); + /// + /// // Count all comments + /// let mut count = 0; + /// comments.for_each(&mut |_| count += 1); + /// + /// // Process comment text (order is not guaranteed) + /// comments.for_each(&mut |comment| { + /// if comment.text.starts_with("//") { + /// println!("Line comment: {}", comment.text); + /// } + /// }); + /// ``` + /// + /// # Performance + /// + /// The `for_each` method provides zero-allocation iteration by: + /// - Directly iterating over the internal data structures + /// - Not creating intermediate collections like `Vec` + /// - Using closure-based iteration instead of returning an iterator + /// + /// This is particularly useful when you need to process all comments but + /// don't need to collect them into a new container. + fn for_each(&self, f: &mut dyn FnMut(&Comment)); + fn with_leading(&self, pos: BytePos, f: F) -> Ret where Self: Sized, @@ -181,6 +219,10 @@ macro_rules! delegate { (**self).add_pure_comment(pos) } + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + (**self).for_each(f) + } + fn has_flag(&self, lo: BytePos, flag: &str) -> bool { (**self).has_flag(lo, flag) } @@ -271,6 +313,11 @@ impl Comments for NoopComments { #[cfg_attr(not(debug_assertions), inline(always))] fn add_pure_comment(&self, _: BytePos) {} + #[cfg_attr(not(debug_assertions), inline(always))] + fn for_each(&self, _f: &mut dyn FnMut(&Comment)) { + // NoopComments has no comments + } + #[inline] fn has_flag(&self, _: BytePos, _: &str) -> bool { false @@ -374,6 +421,12 @@ where } } + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + if let Some(c) = self { + c.for_each(f); + } + } + fn with_leading(&self, pos: BytePos, f: F) -> Ret where Self: Sized, @@ -515,6 +568,26 @@ impl Comments for SingleThreadedComments { } } + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + // Note: Iteration order is unspecified and depends on HashMap iteration order. + // Leading comments are processed first, then trailing comments, but within + // each category the order depends on HashMap's internal structure. + + // Iterate over all leading comments without allocation + for (_, comments) in self.leading.borrow().iter() { + for comment in comments { + f(comment); + } + } + + // Iterate over all trailing comments without allocation + for (_, comments) in self.trailing.borrow().iter() { + for comment in comments { + f(comment); + } + } + } + fn with_leading(&self, pos: BytePos, f: F) -> Ret where Self: Sized, @@ -697,3 +770,84 @@ better_scoped_tls::scoped_tls!( #[doc(hidden)] pub static COMMENTS: Box ); + +#[cfg(test)] +mod tests { + use swc_atoms::atom; + + use super::*; + + #[test] + fn test_for_each_with_comments() { + let comments = SingleThreadedComments::default(); + let pos = BytePos(10); + + let comment = Comment { + kind: CommentKind::Line, + span: Span::new(pos, pos), + text: atom!("// Test comment"), + }; + + comments.add_leading(pos, comment.clone()); + + // Demonstrate for-loop-like usage with for_each + let mut count = 0; + comments.for_each(&mut |_comment| { + count += 1; + }); + + assert_eq!(count, 1); + } + + #[test] + fn test_for_each_empty() { + let comments = SingleThreadedComments::default(); + + let mut count = 0; + comments.for_each(&mut |_comment| { + count += 1; + }); + + assert_eq!(count, 0); + } + + #[test] + fn test_for_each_noop() { + let comments = NoopComments; + + let mut count = 0; + comments.for_each(&mut |_comment| { + count += 1; + }); + + assert_eq!(count, 0); + } + + #[test] + fn test_for_each_option() { + let some_comments = Some(SingleThreadedComments::default()); + let pos = BytePos(10); + + let comment = Comment { + kind: CommentKind::Line, + span: Span::new(pos, pos), + text: atom!("// Test comment"), + }; + + some_comments.add_leading(pos, comment.clone()); + + let mut count = 0; + some_comments.for_each(&mut |_comment| { + count += 1; + }); + assert_eq!(count, 1); + + // Test None case + let none_comments: Option = None; + let mut count_none = 0; + none_comments.for_each(&mut |_comment| { + count_none += 1; + }); + assert_eq!(count_none, 0); + } +} diff --git a/crates/swc_ecma_ast/src/expr.rs b/crates/swc_ecma_ast/src/expr.rs index e91f9c941fb4..d4e0b07a747c 100644 --- a/crates/swc_ecma_ast/src/expr.rs +++ b/crates/swc_ecma_ast/src/expr.rs @@ -183,7 +183,7 @@ impl Expr { span, op: op!("void"), arg: Lit::Num(Number { - span, + span: DUMMY_SP, value: 0.0, raw: None, }) diff --git a/crates/swc_ecma_lexer/src/common/parser/typescript.rs b/crates/swc_ecma_lexer/src/common/parser/typescript.rs index 04c0115a3f8b..70042aa676f5 100644 --- a/crates/swc_ecma_lexer/src/common/parser/typescript.rs +++ b/crates/swc_ecma_lexer/src/common/parser/typescript.rs @@ -64,7 +64,7 @@ where { debug_assert!(p.input().syntax().typescript()); let mut buf = Vec::with_capacity(8); - while !is_ts_list_terminator(p, kind)? { + while !is_ts_list_terminator(p, kind) { // Skipping "parseListElement" from the TS source since that's just for error // handling. buf.push(parse_element(p)?); @@ -111,7 +111,7 @@ where loop { trace_cur!(p, parse_ts_delimited_list_inner__element); - if is_ts_list_terminator(p, kind)? { + if is_ts_list_terminator(p, kind) { break; } @@ -122,7 +122,7 @@ where continue; } - if is_ts_list_terminator(p, kind)? { + if is_ts_list_terminator(p, kind) { break; } @@ -162,23 +162,23 @@ where } /// `tsIsListTerminator` -pub fn is_ts_list_terminator<'a>(p: &mut impl Parser<'a>, kind: ParsingContext) -> PResult { +fn is_ts_list_terminator<'a>(p: &mut impl Parser<'a>, kind: ParsingContext) -> bool { debug_assert!(p.input().syntax().typescript()); let Some(cur) = p.input_mut().cur() else { - return Ok(false); + return false; }; - Ok(match kind { + match kind { ParsingContext::EnumMembers | ParsingContext::TypeMembers => cur.is_rbrace(), ParsingContext::HeritageClauseElement => { cur.is_lbrace() || cur.is_implements() || cur.is_extends() } ParsingContext::TupleElementTypes => cur.is_rbracket(), ParsingContext::TypeParametersOrArguments => cur.is_greater(), - }) + } } /// `tsNextTokenCanFollowModifier` -pub(super) fn ts_next_token_can_follow_modifier<'a>(p: &mut impl Parser<'a>) -> PResult { +fn ts_next_token_can_follow_modifier<'a>(p: &mut impl Parser<'a>) -> bool { debug_assert!(p.input().syntax().typescript()); // Note: TypeScript's implementation is much more complicated because // more things are considered modifiers there. @@ -186,7 +186,7 @@ pub(super) fn ts_next_token_can_follow_modifier<'a>(p: &mut impl Parser<'a>) -> // itself. And "static". TODO: Would be nice to avoid lookahead. Want a // hasLineBreakUpNext() method... p.bump(); - Ok(!p.input_mut().had_line_break_before_cur() + !p.input_mut().had_line_break_before_cur() && p.input_mut().cur().is_some_and(|cur| { cur.is_lbracket() || cur.is_lbrace() @@ -197,7 +197,7 @@ pub(super) fn ts_next_token_can_follow_modifier<'a>(p: &mut impl Parser<'a>) -> || cur.is_str() || cur.is_num() || cur.is_bigint() - })) + }) } /// `tsTryParse` @@ -378,7 +378,7 @@ pub fn parse_ts_modifier<'a, P: Parser<'a>>( { return Ok(None); } - if try_parse_ts_bool(p, |p| ts_next_token_can_follow_modifier(p).map(Some))? { + if try_parse_ts_bool(p, |p| Ok(Some(ts_next_token_can_follow_modifier(p))))? { return Ok(Some(allowed_modifiers[pos])); } } diff --git a/crates/swc_ecma_transforms_optimization/src/inline_globals.rs b/crates/swc_ecma_transforms_optimization/src/inline_globals.rs index c8f1b9f0aca7..abfff8bd6ddf 100644 --- a/crates/swc_ecma_transforms_optimization/src/inline_globals.rs +++ b/crates/swc_ecma_transforms_optimization/src/inline_globals.rs @@ -210,7 +210,7 @@ mod tests { let v = tester .apply_transform( - visit_mut_pass(DropSpan), + |_| visit_mut_pass(DropSpan), "global.js", ::swc_ecma_parser::Syntax::default(), None, diff --git a/crates/swc_ecma_transforms_react/Cargo.toml b/crates/swc_ecma_transforms_react/Cargo.toml index 949e4b7be792..8bd8485dee7b 100644 --- a/crates/swc_ecma_transforms_react/Cargo.toml +++ b/crates/swc_ecma_transforms_react/Cargo.toml @@ -22,6 +22,7 @@ base64 = { workspace = true } bytes-str = { workspace = true } dashmap = { workspace = true } indexmap = { workspace = true } +memchr = { workspace = true } once_cell = { workspace = true } rayon = { workspace = true, optional = true } rustc-hash = { workspace = true } diff --git a/crates/swc_ecma_transforms_react/src/jsx/automatic.rs b/crates/swc_ecma_transforms_react/src/jsx/automatic.rs new file mode 100644 index 000000000000..badfe66fa726 --- /dev/null +++ b/crates/swc_ecma_transforms_react/src/jsx/automatic.rs @@ -0,0 +1,679 @@ +#![allow(clippy::redundant_allocation)] + +use std::iter::once; + +use swc_atoms::{atom, Atom}; +use swc_common::{ + comments::Comments, errors::HANDLER, sync::Lrc, util::take::Take, BytePos, Mark, SourceMap, + Spanned, SyntaxContext, DUMMY_SP, +}; +use swc_ecma_ast::*; +use swc_ecma_utils::{prepend_stmt, private_ident, quote_ident, ExprFactory, StmtLike}; +use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; + +use crate::{ + jsx::{ + development::{visit_mut_development, DevelopmentContext, JsxDev}, + should_use_create_element, + }, + jsx_name, jsx_text_to_str, transform_jsx_attr_str, AutomaticConfig, CommonConfig, +}; + +/// Automatic runtime JSX transformer +/// +/// Transforms JSX using the automatic runtime where imports are injected +/// automatically and JSX elements are converted to jsx() and jsxs() calls. +/// +/// https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md +pub fn automatic( + options: AutomaticConfig, + common: CommonConfig, + unresolved_mark: Mark, + comments: Option, + cm: Lrc, +) -> impl Pass + VisitMut +where + C: Comments + 'static, +{ + let add_pure_comment: Lrc = match comments { + Some(c) => Lrc::new(move |pos: BytePos| { + c.add_pure_comment(pos); + }), + None => Lrc::new(|_pos| {}), + }; + + visit_mut_pass(Automatic { + unresolved_mark, + import_source: options.import_source, + import_jsx: None, + import_jsxs: None, + import_fragment: None, + import_create_element: None, + + throw_if_namespace: common.throw_if_namespace.into_bool(), + + development: common.development.into_bool(), + development_ctx: DevelopmentContext::default(), + + add_pure_comment, + cm, + }) +} + +struct Automatic { + unresolved_mark: Mark, + + import_source: Atom, + import_jsx: Option, + import_jsxs: Option, + import_create_element: Option, + import_fragment: Option, + + throw_if_namespace: bool, + + development: bool, + development_ctx: DevelopmentContext, + + add_pure_comment: Lrc, + cm: Lrc, +} + +impl Automatic { + fn inject_runtime(&mut self, body: &mut Vec, inject: F) + where + T: StmtLike, + F: Fn(Vec<(Ident, IdentName)>, &str, &mut Vec), + { + if let Some(local) = self.import_create_element.take() { + inject( + vec![(local, quote_ident!("createElement"))], + &self.import_source, + body, + ); + } + + let imports = self.import_jsx.take(); + let imports = if self.development { + imports + .map(|local| (local, quote_ident!("jsxDEV"))) + .into_iter() + .chain( + self.import_fragment + .take() + .map(|local| (local, quote_ident!("Fragment"))), + ) + .collect::>() + } else { + imports + .map(|local| (local, quote_ident!("jsx"))) + .into_iter() + .chain( + self.import_jsxs + .take() + .map(|local| (local, quote_ident!("jsxs"))), + ) + .chain( + self.import_fragment + .take() + .map(|local| (local, quote_ident!("Fragment"))), + ) + .collect::>() + }; + + if !imports.is_empty() { + let jsx_runtime = if self.development { + "jsx-dev-runtime" + } else { + "jsx-runtime" + }; + + let value = format!("{}/{}", self.import_source, jsx_runtime); + inject(imports, &value, body) + } + } + + fn jsx_frag_to_expr(&mut self, el: JSXFragment) -> Expr { + let mut span = el.span(); + + if span.lo.is_dummy() { + span.lo = swc_common::Span::dummy_with_cmt().lo; + } + (*self.add_pure_comment)(span.lo); + + let count = count_children(&el.children); + let use_jsxs = count > 1 + || (count == 1 && matches!(&el.children[0], JSXElementChild::JSXSpreadChild(..))); + + let jsx = if use_jsxs && !self.development { + self.import_jsxs + .get_or_insert_with(|| private_ident!("_jsxs")) + .clone() + } else { + let jsx = if self.development { "_jsxDEV" } else { "_jsx" }; + self.import_jsx + .get_or_insert_with(|| private_ident!(jsx)) + .clone() + }; + + let fragment = self + .import_fragment + .get_or_insert_with(|| private_ident!("_Fragment")) + .clone(); + + let mut props_obj = ObjectLit { + span: DUMMY_SP, + props: Vec::new(), + }; + + let children = el + .children + .into_iter() + .filter_map(|child| self.jsx_elem_child_to_expr(child)) + .map(Some) + .collect::>(); + + match (children.len(), use_jsxs) { + (0, _) => {} + (1, false) => { + props_obj + .props + .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: PropName::Ident(quote_ident!("children")), + value: children.into_iter().next().flatten().unwrap().expr, + })))); + } + _ => { + props_obj + .props + .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: PropName::Ident(quote_ident!("children")), + value: ArrayLit { + span: DUMMY_SP, + elems: children, + } + .into(), + })))); + } + } + + let args = once(fragment.as_arg()).chain(once(props_obj.as_arg())); + + let args = if self.development { + args.chain(once(Expr::undefined(DUMMY_SP).as_arg())) + .chain(once(use_jsxs.as_arg())) + .collect() + } else { + args.collect() + }; + + CallExpr { + span, + callee: jsx.as_callee(), + args, + ..Default::default() + } + .into() + } + + ///
=> jsx('div', null); + fn jsx_elem_to_expr(&mut self, el: JSXElement) -> Expr { + let mut span = el.span(); + if span.lo.is_dummy() { + span.lo = swc_common::Span::dummy_with_cmt().lo; + } + (*self.add_pure_comment)(span.lo); + + let use_create_element = should_use_create_element(&el.opening.attrs); + + let name = jsx_name(el.opening.name, self.throw_if_namespace); + + let count = count_children(&el.children); + let use_jsxs = count > 1 + || (count == 1 && matches!(&el.children[0], JSXElementChild::JSXSpreadChild(..))); + + let jsx = if use_create_element { + self.import_create_element + .get_or_insert_with(|| private_ident!("_createElement")) + .clone() + } else if use_jsxs && !self.development { + self.import_jsxs + .get_or_insert_with(|| private_ident!("_jsxs")) + .clone() + } else { + let jsx = if self.development { "_jsxDEV" } else { "_jsx" }; + self.import_jsx + .get_or_insert_with(|| private_ident!(jsx)) + .clone() + }; + + let mut props_obj = ObjectLit { + span: DUMMY_SP, + props: Vec::new(), + }; + + let mut key = None; + + for attr in el.opening.attrs { + match attr { + JSXAttrOrSpread::JSXAttr(attr) => { + // + match attr.name { + JSXAttrName::Ident(i) => { + // + if !use_create_element && i.sym == "key" { + key = attr + .value + .and_then(jsx_attr_value_to_expr) + .map(|expr| expr.as_arg()); + + if key.is_none() { + HANDLER.with(|handler| { + handler + .struct_span_err( + i.span, + "The value of property 'key' should not be empty", + ) + .emit(); + }); + } + continue; + } + + let value = match attr.value { + Some(v) => { + jsx_attr_value_to_expr(v).expect("empty expression container?") + } + None => true.into(), + }; + + // TODO: Check if `i` is a valid identifier. + let key = if i.sym.contains('-') { + PropName::Str(Str { + span: i.span, + raw: None, + value: i.sym, + }) + } else { + PropName::Ident(i) + }; + props_obj + .props + .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key, + value, + })))); + } + JSXAttrName::JSXNamespacedName(JSXNamespacedName { ns, name, .. }) => { + if self.throw_if_namespace { + HANDLER.with(|handler| { + handler + .struct_span_err( + span, + "JSX Namespace is disabled by default because react \ + does not support it yet. You can specify \ + jsc.transform.react.throwIfNamespace to false to \ + override default behavior", + ) + .emit() + }); + } + + let value = match attr.value { + Some(v) => { + jsx_attr_value_to_expr(v).expect("empty expression container?") + } + None => true.into(), + }; + + let str_value = format!("{}:{}", ns.sym, name.sym); + let key = Str { + span, + raw: None, + value: str_value.into(), + }; + let key = PropName::Str(key); + + props_obj + .props + .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key, + value, + })))); + } + } + } + JSXAttrOrSpread::SpreadElement(attr) => match *attr.expr { + Expr::Object(obj) => { + props_obj.props.extend(obj.props); + } + _ => { + props_obj.props.push(PropOrSpread::Spread(attr)); + } + }, + } + } + + let mut children = el + .children + .into_iter() + .filter_map(|child| self.jsx_elem_child_to_expr(child)) + .map(Some) + .collect::>(); + + match children.len() { + 0 => {} + 1 if children[0].as_ref().unwrap().spread.is_none() => { + if !use_create_element { + props_obj + .props + .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: PropName::Ident(quote_ident!("children")), + value: children.take().into_iter().next().flatten().unwrap().expr, + })))); + } + } + _ => { + props_obj + .props + .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: PropName::Ident(quote_ident!("children")), + value: ArrayLit { + span: DUMMY_SP, + elems: children.take(), + } + .into(), + })))); + } + } + + if use_create_element && self.development { + props_obj.props.push( + Prop::KeyValue(KeyValueProp { + key: quote_ident!("__source").into(), + value: self.source_props(el.span.lo).into(), + }) + .into(), + ); + props_obj.props.push( + Prop::KeyValue(KeyValueProp { + key: quote_ident!("__self").into(), + value: self.self_props().into(), + }) + .into(), + ); + } + + let args = once(name.as_arg()).chain(once(props_obj.as_arg())); + let args = if use_create_element { + args.chain(children.into_iter().flatten()).collect() + } else if self.development { + // set undefined literal to key if key is None + let key = match key { + Some(key) => key, + None => Expr::undefined(DUMMY_SP).as_arg(), + }; + + args.chain(once(key)) + .chain(once(use_jsxs.as_arg())) + .chain(once(self.source_props(el.span.lo).as_arg())) + .chain(once(self.self_props().as_arg())) + .collect() + } else { + args.chain(key).collect() + }; + + let mut call_expr = CallExpr { + span, + callee: jsx.as_callee(), + args, + ..Default::default() + }; + + // Add pure comment + if call_expr.span.lo.is_dummy() { + call_expr.span.lo = swc_common::Span::dummy_with_cmt().lo; + } + (*self.add_pure_comment)(call_expr.span.lo); + + call_expr.into() + } + + fn jsx_elem_child_to_expr(&mut self, c: JSXElementChild) -> Option { + Some(match c { + JSXElementChild::JSXText(text) => { + // TODO(kdy1): Optimize + let value = jsx_text_to_str(text.value); + let s = Str { + span: text.span, + raw: None, + value, + }; + + if s.value.is_empty() { + return None; + } + + Lit::Str(s).as_arg() + } + JSXElementChild::JSXExprContainer(JSXExprContainer { + expr: JSXExpr::Expr(e), + .. + }) => e.as_arg(), + JSXElementChild::JSXExprContainer(JSXExprContainer { + expr: JSXExpr::JSXEmptyExpr(..), + .. + }) => return None, + JSXElementChild::JSXElement(el) => self.jsx_elem_to_expr(*el).as_arg(), + JSXElementChild::JSXFragment(el) => self.jsx_frag_to_expr(el).as_arg(), + JSXElementChild::JSXSpreadChild(JSXSpreadChild { span, expr, .. }) => ExprOrSpread { + spread: Some(span), + expr, + }, + }) + } +} + +impl Automatic { + fn source_props(&self, pos: BytePos) -> ObjectLit { + let loc = self.cm.lookup_char_pos(pos); + + ObjectLit { + props: vec![ + Prop::KeyValue(KeyValueProp { + key: quote_ident!("fileName").into(), + value: loc.file.name.to_string().into(), + }) + .into(), + Prop::KeyValue(KeyValueProp { + key: quote_ident!("lineNumber").into(), + value: loc.line.into(), + }) + .into(), + Prop::KeyValue(KeyValueProp { + key: quote_ident!("columnNumber").into(), + value: (loc.col.0 + 1).into(), + }) + .into(), + ], + ..Default::default() + } + } +} + +impl JsxDev for Automatic { + fn development_ctxt(&mut self) -> &mut DevelopmentContext { + &mut self.development_ctx + } +} + +impl VisitMut for Automatic { + noop_visit_mut_type!(); + + visit_mut_development!(); + + fn visit_mut_expr(&mut self, expr: &mut Expr) { + if let Expr::JSXElement(el) = expr { + //
=> React.createElement('div', null); + *expr = self.jsx_elem_to_expr(*el.take()); + } else if let Expr::JSXFragment(frag) = expr { + // <> => React.createElement(React.Fragment, null); + + *expr = self.jsx_frag_to_expr(frag.take()); + } else if let Expr::Paren(ParenExpr { + expr: inner_expr, .. + }) = expr + { + if let Expr::JSXElement(el) = &mut **inner_expr { + *expr = self.jsx_elem_to_expr(*el.take()); + } else if let Expr::JSXFragment(frag) = &mut **inner_expr { + // <> => React.createElement(React.Fragment, null); + *expr = self.jsx_frag_to_expr(frag.take()); + } + } + + expr.visit_mut_children_with(self); + } + + fn visit_mut_module(&mut self, module: &mut Module) { + module.visit_mut_children_with(self); + + self.inject_runtime(&mut module.body, |imports, src, stmts| { + let specifiers = imports + .into_iter() + .map(|(local, imported)| { + ImportSpecifier::Named(ImportNamedSpecifier { + span: DUMMY_SP, + local, + imported: Some(ModuleExportName::Ident(imported.into())), + is_type_only: false, + }) + }) + .collect(); + + prepend_stmt( + stmts, + ImportDecl { + span: DUMMY_SP, + specifiers, + src: Str { + span: DUMMY_SP, + raw: None, + value: src.into(), + } + .into(), + type_only: Default::default(), + with: Default::default(), + phase: Default::default(), + } + .into(), + ) + }); + } + + fn visit_mut_script(&mut self, script: &mut Script) { + script.visit_mut_children_with(self); + + let mark = self.unresolved_mark; + self.inject_runtime(&mut script.body, |imports, src, stmts| { + prepend_stmt(stmts, add_require(imports, src, mark)) + }); + } +} + +// const { createElement } = require('react') +// const { jsx: jsx } = require('react/jsx-runtime') +fn add_require(imports: Vec<(Ident, IdentName)>, src: &str, unresolved_mark: Mark) -> Stmt { + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Const, + declare: false, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: Pat::Object(ObjectPat { + span: DUMMY_SP, + props: imports + .into_iter() + .map(|(local, imported)| { + if imported.sym != local.sym { + ObjectPatProp::KeyValue(KeyValuePatProp { + key: PropName::Ident(imported), + value: Box::new(Pat::Ident(local.into())), + }) + } else { + ObjectPatProp::Assign(AssignPatProp { + span: DUMMY_SP, + key: local.into(), + value: None, + }) + } + }) + .collect(), + optional: false, + type_ann: None, + }), + // require('react') + init: Some(Box::new(Expr::Call(CallExpr { + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Ident(Ident { + ctxt: SyntaxContext::empty().apply_mark(unresolved_mark), + sym: atom!("require"), + optional: false, + ..Default::default() + }))), + args: vec![ExprOrSpread { + spread: None, + expr: Box::new(Expr::Lit(Lit::Str(Str { + span: DUMMY_SP, + value: src.into(), + raw: None, + }))), + }], + ..Default::default() + }))), + definite: false, + }], + ..Default::default() + } + .into() +} + +fn jsx_attr_value_to_expr(v: JSXAttrValue) -> Option> { + Some(match v { + JSXAttrValue::Lit(Lit::Str(s)) => { + let value = transform_jsx_attr_str(&s.value); + + Lit::Str(Str { + span: s.span, + raw: None, + value: value.into(), + }) + .into() + } + JSXAttrValue::Lit(lit) => Box::new(lit.into()), + JSXAttrValue::JSXExprContainer(e) => match e.expr { + JSXExpr::JSXEmptyExpr(_) => None?, + JSXExpr::Expr(e) => e, + }, + JSXAttrValue::JSXElement(e) => e.into(), + JSXAttrValue::JSXFragment(f) => f.into(), + }) +} + +fn count_children(children: &[JSXElementChild]) -> usize { + children + .iter() + .filter(|v| match v { + JSXElementChild::JSXText(text) => { + let text = jsx_text_to_str(text.value.clone()); + !text.is_empty() + } + JSXElementChild::JSXExprContainer(e) => match e.expr { + JSXExpr::JSXEmptyExpr(_) => false, + JSXExpr::Expr(_) => true, + }, + JSXElementChild::JSXSpreadChild(_) => true, + JSXElementChild::JSXElement(_) => true, + JSXElementChild::JSXFragment(_) => true, + }) + .count() +} diff --git a/crates/swc_ecma_transforms_react/src/jsx/classic.rs b/crates/swc_ecma_transforms_react/src/jsx/classic.rs new file mode 100644 index 000000000000..d3168d16010b --- /dev/null +++ b/crates/swc_ecma_transforms_react/src/jsx/classic.rs @@ -0,0 +1,434 @@ +#![allow(clippy::redundant_allocation)] + +use std::{ + iter::{self}, + sync::RwLock, +}; + +use bytes_str::BytesStr; +use once_cell::sync::Lazy; +use rustc_hash::FxHashMap; +use swc_common::{ + comments::Comments, errors::HANDLER, sync::Lrc, util::take::Take, BytePos, FileName, SourceMap, + Spanned, DUMMY_SP, +}; +use swc_ecma_ast::*; +use swc_ecma_parser::{parse_file_as_expr, Syntax}; +use swc_ecma_utils::{drop_span, quote_ident, ExprFactory}; +use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; + +use crate::{ + jsx::development::{visit_mut_development, DevelopmentContext, JsxDev}, + jsx_name, jsx_text_to_str, transform_jsx_attr_str, ClassicConfig, CommonConfig, +}; + +/// Parse `src` to use as a `pragma` or `pragmaFrag` in jsx. +pub fn parse_expr_for_jsx(cm: &SourceMap, name: &str, src: BytesStr) -> Box { + let fm = cm.new_source_file(cache_filename(name), src); + + parse_file_as_expr( + &fm, + Syntax::default(), + Default::default(), + None, + &mut Vec::new(), + ) + .map_err(|e| { + if HANDLER.is_set() { + HANDLER.with(|h| { + e.into_diagnostic(h) + .note("Failed to parse jsx pragma") + .emit() + }) + } + }) + .map(drop_span) + .unwrap_or_else(|()| { + panic!( + "failed to parse jsx option {}: '{}' is not an expression", + name, fm.src, + ) + }) +} + +/// `@babel/plugin-transform-react-jsx` +/// +/// # Parameters +/// +/// ## `pragma_mark` +/// +/// This is used to reference `React` defined by the user. +/// +/// e.g. +/// +/// ```js +/// import React from 'react'; +/// ``` +pub fn classic( + options: ClassicConfig, + common: CommonConfig, + comments: Option, + cm: Lrc, +) -> impl Pass + VisitMut +where + C: Comments + 'static, +{ + let add_pure_comment: Lrc = match comments { + Some(c) => Lrc::new(move |pos: BytePos| { + c.add_pure_comment(pos); + }), + None => Lrc::new(|_pos| {}), + }; + + let pragma = parse_expr_for_jsx(&cm, "pragma", options.pragma); + let pragma = Lrc::new(pragma); + + let pragma_frag = parse_expr_for_jsx(&cm, "pragmaFrag", options.pragma_frag); + let pragma_frag = Lrc::new(pragma_frag); + + visit_mut_pass(Classic { + pragma, + pragma_frag, + + throw_if_namespace: common.throw_if_namespace.into_bool(), + + development: common.development.into_bool(), + development_ctx: DevelopmentContext::default(), + + add_pure_comment, + cm, + }) +} + +struct Classic { + pragma: Lrc>, + pragma_frag: Lrc>, + + throw_if_namespace: bool, + + development: bool, + development_ctx: DevelopmentContext, + + add_pure_comment: Lrc, + cm: Lrc, +} + +#[cfg(feature = "concurrent")] +fn cache_filename(name: &str) -> Lrc { + static FILENAME_CACHE: Lazy>>> = + Lazy::new(|| RwLock::new(FxHashMap::default())); + + { + let cache = FILENAME_CACHE + .read() + .expect("Failed to read FILENAME_CACHE"); + if let Some(f) = cache.get(name) { + return f.clone(); + } + } + + let file = Lrc::new(FileName::Internal(format!("jsx-config-{name}.js"))); + + { + let mut cache = FILENAME_CACHE + .write() + .expect("Failed to write FILENAME_CACHE"); + cache.insert(name.to_string(), file.clone()); + } + + file +} + +#[cfg(not(feature = "concurrent"))] +fn cache_filename(name: &str) -> Lrc { + Lrc::new(FileName::Internal(format!("jsx-config-{name}.js"))) +} + +impl Classic { + fn jsx_frag_to_expr(&mut self, el: JSXFragment) -> Expr { + let mut span = el.span(); + + if span.lo.is_dummy() { + span.lo = swc_common::Span::dummy_with_cmt().lo; + } + (*self.add_pure_comment)(span.lo); + + CallExpr { + span, + callee: (*self.pragma).clone().as_callee(), + args: iter::once((*self.pragma_frag).clone().as_arg()) + // attribute: null + .chain(iter::once(Lit::Null(Null { span: DUMMY_SP }).as_arg())) + .chain({ + // Children + el.children + .into_iter() + .filter_map(|c| self.jsx_elem_child_to_expr(c)) + }) + .collect(), + ..Default::default() + } + .into() + } + + ///
=> React.createElement('div', null); + fn jsx_elem_to_expr(&mut self, el: JSXElement) -> Expr { + let mut span = el.span(); + + if span.lo.is_dummy() { + span.lo = swc_common::Span::dummy_with_cmt().lo; + } + (*self.add_pure_comment)(span.lo); + + let name = jsx_name(el.opening.name, self.throw_if_namespace); + + CallExpr { + span, + callee: (*self.pragma).clone().as_callee(), + args: iter::once(name.as_arg()) + .chain(iter::once({ + // Attributes + self.fold_attrs_for_classic(el.opening.attrs).as_arg() + })) + .chain({ + // Children + el.children + .into_iter() + .filter_map(|c| self.jsx_elem_child_to_expr(c)) + }) + .collect(), + ..Default::default() + } + .into() + } + + fn jsx_elem_child_to_expr(&mut self, c: JSXElementChild) -> Option { + Some(match c { + JSXElementChild::JSXText(text) => { + // TODO(kdy1): Optimize + let value = jsx_text_to_str(text.value); + let s = Str { + span: text.span, + raw: None, + value, + }; + + if s.value.is_empty() { + return None; + } + + Lit::Str(s).as_arg() + } + JSXElementChild::JSXExprContainer(JSXExprContainer { + expr: JSXExpr::Expr(e), + .. + }) => e.as_arg(), + JSXElementChild::JSXExprContainer(JSXExprContainer { + expr: JSXExpr::JSXEmptyExpr(..), + .. + }) => return None, + JSXElementChild::JSXElement(el) => self.jsx_elem_to_expr(*el).as_arg(), + JSXElementChild::JSXFragment(el) => self.jsx_frag_to_expr(el).as_arg(), + JSXElementChild::JSXSpreadChild(JSXSpreadChild { span, expr, .. }) => ExprOrSpread { + spread: Some(span), + expr, + }, + }) + } + + fn fold_attrs_for_classic(&mut self, attrs: Vec) -> Box { + if attrs.is_empty() { + return Lit::Null(Null { span: DUMMY_SP }).into(); + } + let attr_cnt = attrs.len(); + + let mut props = Vec::new(); + for attr in attrs { + match attr { + JSXAttrOrSpread::JSXAttr(attr) => { + props.push(PropOrSpread::Prop(Box::new(self.attr_to_prop(attr)))) + } + JSXAttrOrSpread::SpreadElement(spread) => { + if attr_cnt == 1 { + return spread.expr; + } + // babel does some optimizations + match *spread.expr { + Expr::Object(obj) => props.extend(obj.props), + _ => props.push(PropOrSpread::Spread(spread)), + } + } + } + } + + let obj = ObjectLit { + span: DUMMY_SP, + props, + }; + + obj.into() + } + + fn attr_to_prop(&mut self, a: JSXAttr) -> Prop { + let key = to_prop_name(a.name); + let value = a + .value + .map(|v| match v { + JSXAttrValue::Lit(Lit::Str(s)) => { + let value = transform_jsx_attr_str(&s.value); + + Lit::Str(Str { + span: s.span, + raw: None, + value: value.into(), + }) + .into() + } + JSXAttrValue::JSXExprContainer(JSXExprContainer { + expr: JSXExpr::Expr(e), + .. + }) => e, + JSXAttrValue::JSXElement(element) => Box::new(self.jsx_elem_to_expr(*element)), + JSXAttrValue::JSXFragment(fragment) => Box::new(self.jsx_frag_to_expr(fragment)), + JSXAttrValue::Lit(lit) => Box::new(lit.into()), + JSXAttrValue::JSXExprContainer(JSXExprContainer { + span: _, + expr: JSXExpr::JSXEmptyExpr(_), + }) => unreachable!("attr_to_prop(JSXEmptyExpr)"), + }) + .unwrap_or_else(|| { + Lit::Bool(Bool { + span: key.span(), + value: true, + }) + .into() + }); + Prop::KeyValue(KeyValueProp { key, value }) + } +} + +impl JsxDev for Classic { + fn development_ctxt(&mut self) -> &mut DevelopmentContext { + &mut self.development_ctx + } +} + +impl VisitMut for Classic { + noop_visit_mut_type!(); + + visit_mut_development!(); + + fn visit_mut_expr(&mut self, expr: &mut Expr) { + expr.visit_mut_children_with(self); + + if let Expr::JSXElement(el) = expr { + //
=> React.createElement('div', null); + *expr = self.jsx_elem_to_expr(*el.take()); + } else if let Expr::JSXFragment(frag) = expr { + // <> => React.createElement(React.Fragment, null); + + *expr = self.jsx_frag_to_expr(frag.take()); + } else if let Expr::Paren(ParenExpr { + expr: inner_expr, .. + }) = expr + { + if let Expr::JSXElement(el) = &mut **inner_expr { + *expr = self.jsx_elem_to_expr(*el.take()); + } else if let Expr::JSXFragment(frag) = &mut **inner_expr { + // <> => React.createElement(React.Fragment, null); + + *expr = self.jsx_frag_to_expr(frag.take()); + } + } + } + + fn visit_mut_jsx_opening_element(&mut self, e: &mut JSXOpeningElement) { + e.visit_mut_children_with(self); + + if !self.development { + return; + } + + let loc = self.cm.lookup_char_pos(e.span.lo); + let file_name = loc.file.name.to_string(); + + e.attrs.push( + JSXAttr { + span: DUMMY_SP, + name: quote_ident!("__source").into(), + value: Some( + JSXExprContainer { + span: DUMMY_SP, + expr: JSXExpr::Expr( + ObjectLit { + span: DUMMY_SP, + props: vec![ + Prop::KeyValue(KeyValueProp { + key: quote_ident!("fileName").into(), + value: file_name.into(), + }) + .into(), + Prop::KeyValue(KeyValueProp { + key: quote_ident!("lineNumber").into(), + value: loc.line.into(), + }) + .into(), + Prop::KeyValue(KeyValueProp { + key: quote_ident!("columnNumber").into(), + value: (loc.col.0 + 1).into(), + }) + .into(), + ], + } + .into(), + ), + } + .into(), + ), + } + .into(), + ); + + e.attrs.push( + JSXAttr { + span: DUMMY_SP, + name: quote_ident!("__self").into(), + value: Some( + JSXExprContainer { + span: DUMMY_SP, + expr: JSXExpr::Expr(self.self_props().into()), + } + .into(), + ), + } + .into(), + ); + } +} + +fn to_prop_name(n: JSXAttrName) -> PropName { + let span = n.span(); + + match n { + JSXAttrName::Ident(i) => { + if i.sym.contains('-') { + PropName::Str(Str { + span, + raw: None, + value: i.sym, + }) + } else { + PropName::Ident(i) + } + } + JSXAttrName::JSXNamespacedName(JSXNamespacedName { ns, name, .. }) => { + let value = format!("{}:{}", ns.sym, name.sym); + + PropName::Str(Str { + span, + raw: None, + value: value.into(), + }) + } + } +} diff --git a/crates/swc_ecma_transforms_react/src/jsx/development.rs b/crates/swc_ecma_transforms_react/src/jsx/development.rs new file mode 100644 index 000000000000..3954af184054 --- /dev/null +++ b/crates/swc_ecma_transforms_react/src/jsx/development.rs @@ -0,0 +1,95 @@ +use swc_common::{util::take::Take, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_visit::{VisitMut, VisitMutWith}; + +/// Context for tracking jsx self state +#[derive(Clone, Copy, Default)] +pub(crate) struct DevelopmentContext { + pub in_constructor: bool, + pub in_derived_class: bool, +} + +pub(crate) trait JsxDev: VisitMut { + fn development_ctxt(&mut self) -> &mut DevelopmentContext; + + /// Helper method to run a closure with modified in_constructor state + fn with_in_constructor>(&mut self, in_constructor: bool, n: &mut N) { + let ctxt = *self.development_ctxt(); + self.development_ctxt().in_constructor = in_constructor; + n.visit_mut_children_with(self); + *self.development_ctxt() = ctxt; + } + + fn visit_mut_class(&mut self, n: &mut Class) { + let ctxt = *self.development_ctxt(); + self.development_ctxt().in_derived_class = n.super_class.is_some(); + n.visit_mut_children_with(self); + *self.development_ctxt() = ctxt; + } + + fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) { + self.with_in_constructor(false, n); + } + + fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) { + self.with_in_constructor(false, n); + } + + fn visit_mut_prop(&mut self, n: &mut Prop) { + match n { + Prop::Getter(_) | Prop::Setter(_) | Prop::Method(_) => { + self.with_in_constructor(false, n) + } + _ => n.visit_mut_children_with(self), + } + } + + fn visit_mut_class_member(&mut self, n: &mut ClassMember) { + match n { + ClassMember::Constructor(_) => self.with_in_constructor(true, n), + ClassMember::Method(_) + | ClassMember::PrivateMethod(_) + | ClassMember::StaticBlock(_) => self.with_in_constructor(false, n), + _ => n.visit_mut_children_with(self), + } + } + + /// https://github.com/babel/babel/blob/1bdb1a4175ed1fc40751fb84dc4ad1900260f28f/packages/babel-plugin-transform-react-jsx-self/src/index.ts#L50 + fn is_this_allowed(&mut self) -> bool { + !(self.development_ctxt().in_constructor && self.development_ctxt().in_derived_class) + } + + fn self_props(&mut self) -> Expr { + if self.is_this_allowed() { + Expr::This(ThisExpr::dummy()) + } else { + *Expr::undefined(DUMMY_SP) + } + } +} + +macro_rules! visit_mut_development { + () => { + fn visit_mut_class(&mut self, n: &mut Class) { + JsxDev::visit_mut_class(self, n); + } + + fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) { + JsxDev::visit_mut_fn_decl(self, n); + } + + fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) { + JsxDev::visit_mut_fn_expr(self, n); + } + + fn visit_mut_prop(&mut self, n: &mut Prop) { + JsxDev::visit_mut_prop(self, n); + } + + fn visit_mut_class_member(&mut self, n: &mut ClassMember) { + JsxDev::visit_mut_class_member(self, n); + } + }; +} + +pub(crate) use visit_mut_development; diff --git a/crates/swc_ecma_transforms_react/src/jsx/mod.rs b/crates/swc_ecma_transforms_react/src/jsx/mod.rs index 5177bc101926..b1668027a9cb 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/mod.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/mod.rs @@ -1,1383 +1,258 @@ #![allow(clippy::redundant_allocation)] -use std::{ - borrow::Cow, - iter::{self, once}, - sync::RwLock, -}; +use std::borrow::Cow; use bytes_str::BytesStr; use once_cell::sync::Lazy; -use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; -use string_enum::StringEnum; use swc_atoms::{atom, Atom}; -use swc_common::{ - comments::{Comment, CommentKind, Comments}, - errors::HANDLER, - iter::IdentifyLast, - sync::Lrc, - util::take::Take, - FileName, Mark, SourceMap, Span, Spanned, SyntaxContext, DUMMY_SP, -}; -use swc_config::merge::Merge; +use swc_common::{iter::IdentifyLast, Spanned}; +use swc_config::{merge::Merge, types::BoolConfig}; use swc_ecma_ast::*; -use swc_ecma_parser::{parse_file_as_expr, Syntax}; -use swc_ecma_utils::{drop_span, prepend_stmt, private_ident, quote_ident, ExprFactory, StmtLike}; -use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; use self::static_check::should_use_create_element; use crate::refresh::options::{deserialize_refresh, RefreshOptions}; +mod automatic; +mod classic; +mod development; +mod parse_directives; mod static_check; -#[cfg(test)] -mod tests; -/// https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#runtime -#[derive(StringEnum, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)] -pub enum Runtime { - /// `automatic` - Automatic, - /// `classic` - Classic, -} +pub use automatic::automatic; +pub use classic::{classic, parse_expr_for_jsx}; +pub use parse_directives::parse_directives; -/// Note: This will changed in v2 -impl Default for Runtime { - fn default() -> Self { - Runtime::Classic - } -} +#[cfg(test)] +mod tests; -#[derive(Debug, Default, Clone, Serialize, Deserialize, Eq, PartialEq, Merge)] +#[derive(Debug, Default, Clone, Copy, Deserialize, Serialize, Merge)] #[serde(rename_all = "camelCase")] -#[serde(deny_unknown_fields)] -pub struct Options { - /// If this is `true`, swc will behave just like babel 8 with - /// `BABEL_8_BREAKING: true`. - #[serde(skip, default)] - pub next: Option, - +pub struct CommonConfig { #[serde(default)] - pub runtime: Option, - - /// For automatic runtime + pub development: BoolConfig, #[serde(default)] - pub import_source: Option, - - #[serde(default)] - pub pragma: Option, - #[serde(default)] - pub pragma_frag: Option, - + pub pure: BoolConfig, #[serde(default)] - pub throw_if_namespace: Option, - - #[serde(default)] - pub development: Option, - - // @babel/plugin-transform-react-jsx: Since "useBuiltIns" is removed in Babel 8, you can remove - // it from the config. - #[deprecated( - since = "0.167.4", - note = r#"Since `useBuiltIns` is removed in swc, you can remove it from the config."# - )] - #[serde(default, alias = "useBuiltIns")] - pub use_builtins: Option, - - // '@babel/plugin-transform-react-jsx: Since Babel 8, an inline object with spread elements is - // always used, and the "useSpread" option is no longer available. Please remove it from your - // config.', - #[deprecated( - since = "0.167.4", - note = r#"An inline object with spread elements is always used, and the `useSpread` option is no longer available. Please remove it from your config."# - )] - #[serde(default)] - pub use_spread: Option, - - #[serde(default, deserialize_with = "deserialize_refresh")] - // default to disabled since this is still considered as experimental by now - pub refresh: Option, -} - -#[cfg(feature = "concurrent")] -macro_rules! static_str { - ($s:expr) => {{ - static VAL: Lazy = Lazy::new(|| $s.into()); - VAL.clone() - }}; -} - -#[cfg(not(feature = "concurrent"))] -macro_rules! static_str { - ($s:expr) => { - $s.into() - }; -} - -pub fn default_import_source() -> Atom { - atom!("react") -} - -pub fn default_pragma() -> BytesStr { - static_str!("React.createElement") -} - -pub fn default_pragma_frag() -> BytesStr { - static_str!("React.Fragment") + pub throw_if_namespace: BoolConfig, } -fn default_throw_if_namespace() -> bool { - true -} - -/// Parse `src` to use as a `pragma` or `pragmaFrag` in jsx. -pub fn parse_expr_for_jsx( - cm: &SourceMap, - name: &str, - src: BytesStr, - top_level_mark: Mark, -) -> Box { - let fm = cm.new_source_file(cache_filename(name), src); - - parse_file_as_expr( - &fm, - Syntax::default(), - Default::default(), - None, - &mut Vec::new(), - ) - .map_err(|e| { - if HANDLER.is_set() { - HANDLER.with(|h| { - e.into_diagnostic(h) - .note("Failed to parse jsx pragma") - .emit() - }) - } - }) - .map(drop_span) - .map(|mut expr| { - apply_mark(&mut expr, top_level_mark); - expr - }) - .unwrap_or_else(|()| { - panic!( - "failed to parse jsx option {}: '{}' is not an expression", - name, fm.src, - ) - }) +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +pub struct AutomaticConfig { + /// Import source for automatic runtime + #[serde(default = "default_import_source")] + pub import_source: Atom, } -fn apply_mark(e: &mut Expr, mark: Mark) { - match e { - Expr::Ident(i) => { - i.ctxt = i.ctxt.apply_mark(mark); - } - Expr::Member(MemberExpr { obj, .. }) => { - apply_mark(obj, mark); +impl Default for AutomaticConfig { + fn default() -> Self { + Self { + import_source: default_import_source(), } - _ => {} } } -/// `@babel/plugin-transform-react-jsx` -/// -/// Turn JSX into React function calls -/// -/// -/// `top_level_mark` should be [Mark] passed to -/// [swc_ecma_transforms_base::resolver::resolver_with_mark]. -/// -/// -/// # Parameters -/// -/// ## `top_level_ctxt` -/// -/// This is used to reference `React` defined by the user. -/// -/// e.g. -/// -/// ```js -/// import React from 'react'; -/// ``` -pub fn jsx( - cm: Lrc, - comments: Option, - options: Options, - top_level_mark: Mark, - unresolved_mark: Mark, -) -> impl Pass + VisitMut -where - C: Comments, -{ - visit_mut_pass(Jsx { - cm: cm.clone(), - top_level_mark, - unresolved_mark, - runtime: options.runtime.unwrap_or_default(), - import_source: options.import_source.unwrap_or_else(default_import_source), - import_jsx: None, - import_jsxs: None, - import_fragment: None, - import_create_element: None, - - pragma: Lrc::new(parse_expr_for_jsx( - &cm, - "pragma", - options.pragma.unwrap_or_else(default_pragma), - top_level_mark, - )), - comments, - pragma_frag: Lrc::new(parse_expr_for_jsx( - &cm, - "pragmaFrag", - options.pragma_frag.unwrap_or_else(default_pragma_frag), - top_level_mark, - )), - development: options.development.unwrap_or_default(), - throw_if_namespace: options - .throw_if_namespace - .unwrap_or_else(default_throw_if_namespace), - top_level_node: true, - }) -} - -struct Jsx -where - C: Comments, -{ - cm: Lrc, - - top_level_mark: Mark, - unresolved_mark: Mark, - - runtime: Runtime, - /// For automatic runtime. - import_source: Atom, - /// For automatic runtime. - import_jsx: Option, - /// For automatic runtime. - import_jsxs: Option, - /// For automatic runtime. - import_create_element: Option, - /// For automatic runtime. - import_fragment: Option, - top_level_node: bool, - - pragma: Lrc>, - comments: Option, - pragma_frag: Lrc>, - development: bool, - throw_if_namespace: bool, -} - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub struct JsxDirectives { - pub runtime: Option, - - /// For automatic runtime. - pub import_source: Option, - - /// Parsed from `@jsx` - pub pragma: Option>>, - - /// Parsed from `@jsxFrag` - pub pragma_frag: Option>>, +/// Configuration for classic JSX runtime transformation +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClassicConfig { + /// The pragma for JSX elements (e.g., "React.createElement") + #[serde(default = "default_pragma")] + pub pragma: BytesStr, + + /// The pragma for JSX fragments (e.g., "React.Fragment") + #[serde(default = "default_pragma_frag")] + pub pragma_frag: BytesStr, } -fn respan(e: &mut Expr, span: Span) { - match e { - Expr::Ident(i) => { - i.span.lo = span.lo; - i.span.hi = span.hi; - } - Expr::Member(e) => { - e.span = span; +impl Default for ClassicConfig { + fn default() -> Self { + Self { + pragma: default_pragma(), + pragma_frag: default_pragma_frag(), } - _ => {} } } -impl JsxDirectives { - pub fn from_comments( - cm: &SourceMap, - _: Span, - comments: &[Comment], - top_level_mark: Mark, - ) -> Self { - let mut res = JsxDirectives::default(); - - for cmt in comments { - if cmt.kind != CommentKind::Block { - continue; - } - - for line in cmt.text.lines() { - let mut line = line.trim(); - if line.starts_with('*') { - line = line[1..].trim(); - } - - if !line.starts_with("@jsx") { - continue; - } - - let mut words = line.split_whitespace(); - loop { - let pragma = words.next(); - if pragma.is_none() { - break; - } - let val = words.next(); - - match pragma { - Some("@jsxRuntime") => match val { - Some("classic") => res.runtime = Some(Runtime::Classic), - Some("automatic") => res.runtime = Some(Runtime::Automatic), - None => {} - _ => { - HANDLER.with(|handler| { - handler - .struct_span_err( - cmt.span, - "Runtime must be either `classic` or `automatic`.", - ) - .emit() - }); - } - }, - Some("@jsxImportSource") => { - if let Some(src) = val { - res.runtime = Some(Runtime::Automatic); - res.import_source = Some(Atom::new(src)); - } - } - Some("@jsxFrag") => { - if let Some(src) = val { - if is_valid_for_pragma(src) { - // TODO: Optimize - let mut e = parse_expr_for_jsx( - cm, - "module-jsx-pragma-frag", - cache_source(src), - top_level_mark, - ); - respan(&mut e, cmt.span); - res.pragma_frag = Some(e.into()) - } - } - } - Some("@jsx") => { - if let Some(src) = val { - if is_valid_for_pragma(src) { - // TODO: Optimize - let mut e = parse_expr_for_jsx( - cm, - "module-jsx-pragma", - cache_source(src), - top_level_mark, - ); - respan(&mut e, cmt.span); - res.pragma = Some(e.into()); - } - } - } - _ => {} - } - } - } - } - - res - } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(try_from = "RuntimeRaw")] +pub enum Runtime { + Classic(ClassicConfig), + Automatic(AutomaticConfig), + Preserve, } -#[cfg(feature = "concurrent")] -fn cache_filename(name: &str) -> Lrc { - static FILENAME_CACHE: Lazy>>> = - Lazy::new(|| RwLock::new(FxHashMap::default())); - - { - let cache = FILENAME_CACHE - .read() - .expect("Failed to read FILENAME_CACHE"); - if let Some(f) = cache.get(name) { - return f.clone(); - } - } - - let file = Lrc::new(FileName::Internal(format!("jsx-config-{name}.js"))); - - { - let mut cache = FILENAME_CACHE - .write() - .expect("Failed to write FILENAME_CACHE"); - cache.insert(name.to_string(), file.clone()); +impl Default for Runtime { + fn default() -> Self { + Runtime::Automatic(Default::default()) } - - file -} - -#[cfg(not(feature = "concurrent"))] -fn cache_filename(name: &str) -> Lrc { - Lrc::new(FileName::Internal(format!("jsx-config-{name}.js"))) } -#[cfg(feature = "concurrent")] -fn cache_source(src: &str) -> BytesStr { - use rustc_hash::FxHashSet; - - static CACHE: Lazy>> = - Lazy::new(|| RwLock::new(FxHashSet::default())); - - { - let cache = CACHE.write().unwrap(); - - if let Some(cached) = cache.get(src) { - return cached.clone(); - } +impl Merge for Runtime { + fn merge(&mut self, other: Self) { + *self = other; } - - let cached: BytesStr = src.to_string().into(); - { - let mut cache = CACHE.write().unwrap(); - cache.insert(cached.clone()); - } - cached -} - -#[cfg(not(feature = "concurrent"))] -fn cache_source(src: &str) -> BytesStr { - // We cannot cache because Rc does not implement Send. - src.to_string().into() } -fn is_valid_for_pragma(s: &str) -> bool { - if s.is_empty() { - return false; - } - - if !s.starts_with(|c: char| Ident::is_valid_start(c)) { - return false; - } - - for c in s.chars() { - if !Ident::is_valid_continue(c) && c != '.' { - return false; - } - } - - true +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RuntimeRaw { + #[serde(default)] + runtime: Option, + #[serde(default)] + pragma: Option, + #[serde(default)] + pragma_frag: Option, + #[serde(default)] + import_source: Option, } -impl Jsx -where - C: Comments, -{ - fn inject_runtime(&mut self, body: &mut Vec, inject: F) - where - T: StmtLike, - // Fn(Vec<(local, imported)>, src, body) - F: Fn(Vec<(Ident, IdentName)>, &str, &mut Vec), - { - if self.runtime == Runtime::Automatic { - if let Some(local) = self.import_create_element.take() { - inject( - vec![(local, quote_ident!("createElement"))], - &self.import_source, - body, - ); - } - - let imports = self.import_jsx.take(); - let imports = if self.development { - imports - .map(|local| (local, quote_ident!("jsxDEV"))) - .into_iter() - .chain( - self.import_fragment - .take() - .map(|local| (local, quote_ident!("Fragment"))), - ) - .collect::>() - } else { - imports - .map(|local| (local, quote_ident!("jsx"))) - .into_iter() - .chain( - self.import_jsxs - .take() - .map(|local| (local, quote_ident!("jsxs"))), - ) - .chain( - self.import_fragment - .take() - .map(|local| (local, quote_ident!("Fragment"))), - ) - .collect::>() - }; - - if !imports.is_empty() { - let jsx_runtime = if self.development { - "jsx-dev-runtime" - } else { - "jsx-runtime" - }; - - let value = format!("{}/{}", self.import_source, jsx_runtime); - inject(imports, &value, body) - } - } - } - - fn jsx_frag_to_expr(&mut self, el: JSXFragment) -> Expr { - let mut span = el.span(); - - let count = count_children(&el.children); - let use_jsxs = count > 1 - || (count == 1 && matches!(&el.children[0], JSXElementChild::JSXSpreadChild(..))); - - if let Some(comments) = &self.comments { - if span.lo.is_dummy() { - span.lo = Span::dummy_with_cmt().lo; - } - - comments.add_pure_comment(span.lo); - } - - match self.runtime { - Runtime::Automatic => { - let jsx = if use_jsxs && !self.development { - self.import_jsxs - .get_or_insert_with(|| private_ident!("_jsxs")) - .clone() - } else { - let jsx = if self.development { "_jsxDEV" } else { "_jsx" }; - self.import_jsx - .get_or_insert_with(|| private_ident!(jsx)) - .clone() - }; - - let fragment = self - .import_fragment - .get_or_insert_with(|| private_ident!("_Fragment")) - .clone(); - - let mut props_obj = ObjectLit { - span: DUMMY_SP, - props: Vec::new(), - }; - - let children = el - .children - .into_iter() - .filter_map(|child| self.jsx_elem_child_to_expr(child)) - .map(Some) - .collect::>(); - - match (children.len(), use_jsxs) { - (0, _) => {} - (1, false) => { - props_obj - .props - .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("children")), - value: children.into_iter().next().flatten().unwrap().expr, - })))); - } - _ => { - props_obj - .props - .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("children")), - value: ArrayLit { - span: DUMMY_SP, - elems: children, - } - .into(), - })))); - } - } - - let args = once(fragment.as_arg()).chain(once(props_obj.as_arg())); - - let args = if self.development { - args.chain(once(Expr::undefined(DUMMY_SP).as_arg())) - .chain(once(use_jsxs.as_arg())) - .collect() - } else { - args.collect() - }; - - CallExpr { - span, - callee: jsx.as_callee(), - args, - ..Default::default() - } - .into() - } - Runtime::Classic => { - CallExpr { - span, - callee: (*self.pragma).clone().as_callee(), - args: iter::once((*self.pragma_frag).clone().as_arg()) - // attribute: null - .chain(iter::once(Lit::Null(Null { span: DUMMY_SP }).as_arg())) - .chain({ - // Children - el.children - .into_iter() - .filter_map(|c| self.jsx_elem_child_to_expr(c)) - }) - .collect(), - ..Default::default() - } - .into() - } - } - } - - /// # Automatic - /// - ///
=> jsx('div', null); - /// - /// # Classic - /// - ///
=> React.createElement('div', null); - fn jsx_elem_to_expr(&mut self, el: JSXElement) -> Expr { - let top_level_node = self.top_level_node; - let mut span = el.span(); - let use_create_element = should_use_create_element(&el.opening.attrs); - self.top_level_node = false; - - let name = self.jsx_name(el.opening.name); - - if let Some(comments) = &self.comments { - if span.lo.is_dummy() { - span.lo = Span::dummy_with_cmt().lo; - } - - comments.add_pure_comment(span.lo); - } - - match self.runtime { - Runtime::Automatic => { - // function jsx(tagName: string, props: { children: Node[], ... }, key: string) - - let count = count_children(&el.children); - let use_jsxs = count > 1 - || (count == 1 - && matches!(&el.children[0], JSXElementChild::JSXSpreadChild(..))); - - let jsx = if use_create_element { - self.import_create_element - .get_or_insert_with(|| private_ident!("_createElement")) - .clone() - } else if use_jsxs && !self.development { - self.import_jsxs - .get_or_insert_with(|| private_ident!("_jsxs")) - .clone() - } else { - let jsx = if self.development { "_jsxDEV" } else { "_jsx" }; - self.import_jsx - .get_or_insert_with(|| private_ident!(jsx)) - .clone() - }; - - let mut props_obj = ObjectLit { - span: DUMMY_SP, - props: Vec::new(), - }; - - let mut key = None; - let mut source_props = None; - let mut self_props = None; - - for attr in el.opening.attrs { - match attr { - JSXAttrOrSpread::JSXAttr(attr) => { - // - match attr.name { - JSXAttrName::Ident(i) => { - // - if !use_create_element && i.sym == "key" { - key = attr - .value - .and_then(jsx_attr_value_to_expr) - .map(|expr| expr.as_arg()); - - if key.is_none() { - HANDLER.with(|handler| { - handler - .struct_span_err( - i.span, - "The value of property 'key' should not \ - be empty", - ) - .emit(); - }); - } - continue; - } - - if !use_create_element - && *i.sym == *"__source" - && self.development - { - if source_props.is_some() { - panic!("Duplicate __source is found"); - } - source_props = attr - .value - .and_then(jsx_attr_value_to_expr) - .map(|expr| expr.as_arg()); - assert_ne!( - source_props, None, - "value of property '__source' should not be empty" - ); - continue; - } - - if !use_create_element - && *i.sym == *"__self" - && self.development - { - if self_props.is_some() { - panic!("Duplicate __self is found"); - } - self_props = attr - .value - .and_then(jsx_attr_value_to_expr) - .map(|expr| expr.as_arg()); - assert_ne!( - self_props, None, - "value of property '__self' should not be empty" - ); - continue; - } - - let value = match attr.value { - Some(v) => jsx_attr_value_to_expr(v) - .expect("empty expression container?"), - None => true.into(), - }; - - // TODO: Check if `i` is a valid identifier. - let key = if i.sym.contains('-') { - PropName::Str(Str { - span: i.span, - raw: None, - value: i.sym, - }) - } else { - PropName::Ident(i) - }; - props_obj.props.push(PropOrSpread::Prop(Box::new( - Prop::KeyValue(KeyValueProp { key, value }), - ))); - } - JSXAttrName::JSXNamespacedName(JSXNamespacedName { - ns, - name, - .. - }) => { - if self.throw_if_namespace { - HANDLER.with(|handler| { - handler - .struct_span_err( - span, - "JSX Namespace is disabled by default because \ - react does not support it yet. You can \ - specify jsc.transform.react.throwIfNamespace \ - to false to override default behavior", - ) - .emit() - }); - } - - let value = match attr.value { - Some(v) => jsx_attr_value_to_expr(v) - .expect("empty expression container?"), - None => true.into(), - }; - - let str_value = format!("{}:{}", ns.sym, name.sym); - let key = Str { - span, - raw: None, - value: str_value.into(), - }; - let key = PropName::Str(key); - - props_obj.props.push(PropOrSpread::Prop(Box::new( - Prop::KeyValue(KeyValueProp { key, value }), - ))); - } - } - } - JSXAttrOrSpread::SpreadElement(attr) => match *attr.expr { - Expr::Object(obj) => { - props_obj.props.extend(obj.props); - } - _ => { - props_obj.props.push(PropOrSpread::Spread(attr)); - } - }, - } - } - - let mut children = el - .children - .into_iter() - .filter_map(|child| self.jsx_elem_child_to_expr(child)) - .map(Some) - .collect::>(); - - match children.len() { - 0 => {} - 1 if children[0].as_ref().unwrap().spread.is_none() => { - if !use_create_element { - props_obj - .props - .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("children")), - value: children - .take() - .into_iter() - .next() - .flatten() - .unwrap() - .expr, - })))); - } - } - _ => { - props_obj - .props - .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("children")), - value: ArrayLit { - span: DUMMY_SP, - elems: children.take(), - } - .into(), - })))); - } - } - - self.top_level_node = top_level_node; - - let args = once(name.as_arg()).chain(once(props_obj.as_arg())); - let args = if use_create_element { - args.chain(children.into_iter().flatten()).collect() - } else if self.development { - // set undefined literal to key if key is None - let key = match key { - Some(key) => key, - None => Expr::undefined(DUMMY_SP).as_arg(), - }; - - // set undefined literal to __source if __source is None - let source_props = match source_props { - Some(source_props) => source_props, - None => Expr::undefined(DUMMY_SP).as_arg(), - }; - - // set undefined literal to __self if __self is None - let self_props = match self_props { - Some(self_props) => self_props, - None => Expr::undefined(DUMMY_SP).as_arg(), - }; - args.chain(once(key)) - .chain(once(use_jsxs.as_arg())) - .chain(once(source_props)) - .chain(once(self_props)) - .collect() - } else { - args.chain(key).collect() - }; - CallExpr { - span, - callee: jsx.as_callee(), - args, - ..Default::default() - } - .into() - } - Runtime::Classic => { - CallExpr { - span, - callee: (*self.pragma).clone().as_callee(), - args: iter::once(name.as_arg()) - .chain(iter::once({ - // Attributes - self.fold_attrs_for_classic(el.opening.attrs).as_arg() - })) - .chain({ - // Children - el.children - .into_iter() - .filter_map(|c| self.jsx_elem_child_to_expr(c)) - }) - .collect(), - ..Default::default() - } - .into() - } - } - } - - fn jsx_elem_child_to_expr(&mut self, c: JSXElementChild) -> Option { - self.top_level_node = false; - - Some(match c { - JSXElementChild::JSXText(text) => { - // TODO(kdy1): Optimize - let value = jsx_text_to_str(text.value); - let s = Str { - span: text.span, - raw: None, - value, - }; - - if s.value.is_empty() { - return None; +impl TryFrom for Runtime { + type Error = String; + + fn try_from(raw: RuntimeRaw) -> Result { + match raw.runtime.as_deref() { + Some("automatic") => Ok(Runtime::Automatic(AutomaticConfig { + import_source: raw.import_source.unwrap_or_else(default_import_source), + })), + Some("classic") => Ok(Runtime::Classic(ClassicConfig { + pragma: raw.pragma.unwrap_or_else(default_pragma), + pragma_frag: raw.pragma_frag.unwrap_or_else(default_pragma_frag), + })), + Some("preserve") => Ok(Runtime::Preserve), + Some(other) => Err(format!( + "unknown runtime variant `{other}`, expected one of `automatic`, `classic`, \ + `preserve`" + )), + None => match (raw.pragma, raw.pragma_frag, raw.import_source) { + (pragma @ Some(..), pragma_frag, None) | (pragma, pragma_frag @ Some(..), None) => { + Ok(Runtime::Classic(ClassicConfig { + pragma: pragma.unwrap_or_else(default_pragma), + pragma_frag: pragma_frag.unwrap_or_else(default_pragma_frag), + })) } - - Lit::Str(s).as_arg() - } - JSXElementChild::JSXExprContainer(JSXExprContainer { - expr: JSXExpr::Expr(e), - .. - }) => e.as_arg(), - JSXElementChild::JSXExprContainer(JSXExprContainer { - expr: JSXExpr::JSXEmptyExpr(..), - .. - }) => return None, - JSXElementChild::JSXElement(el) => self.jsx_elem_to_expr(*el).as_arg(), - JSXElementChild::JSXFragment(el) => self.jsx_frag_to_expr(el).as_arg(), - JSXElementChild::JSXSpreadChild(JSXSpreadChild { span, expr, .. }) => ExprOrSpread { - spread: Some(span), - expr, + (_, _, import_source) => Ok(Runtime::Automatic(AutomaticConfig { + import_source: import_source.unwrap_or_else(default_import_source), + })), }, - }) - } - - fn fold_attrs_for_classic(&mut self, attrs: Vec) -> Box { - if attrs.is_empty() { - return Lit::Null(Null { span: DUMMY_SP }).into(); } - let attr_cnt = attrs.len(); - - let mut props = Vec::new(); - for attr in attrs { - match attr { - JSXAttrOrSpread::JSXAttr(attr) => { - props.push(PropOrSpread::Prop(Box::new(self.attr_to_prop(attr)))) - } - JSXAttrOrSpread::SpreadElement(spread) => { - if attr_cnt == 1 { - return spread.expr; - } - // babel does some optimizations - match *spread.expr { - Expr::Object(obj) => props.extend(obj.props), - _ => props.push(PropOrSpread::Spread(spread)), - } - } - } - } - - let obj = ObjectLit { - span: DUMMY_SP, - props, - }; - - obj.into() - } - - fn attr_to_prop(&mut self, a: JSXAttr) -> Prop { - let key = to_prop_name(a.name); - let value = a - .value - .map(|v| match v { - JSXAttrValue::Lit(Lit::Str(s)) => { - let value = transform_jsx_attr_str(&s.value); - - Lit::Str(Str { - span: s.span, - raw: None, - value: value.into(), - }) - .into() - } - JSXAttrValue::JSXExprContainer(JSXExprContainer { - expr: JSXExpr::Expr(e), - .. - }) => e, - JSXAttrValue::JSXElement(element) => Box::new(self.jsx_elem_to_expr(*element)), - JSXAttrValue::JSXFragment(fragment) => Box::new(self.jsx_frag_to_expr(fragment)), - JSXAttrValue::Lit(lit) => Box::new(lit.into()), - JSXAttrValue::JSXExprContainer(JSXExprContainer { - span: _, - expr: JSXExpr::JSXEmptyExpr(_), - }) => unreachable!("attr_to_prop(JSXEmptyExpr)"), - }) - .unwrap_or_else(|| { - Lit::Bool(Bool { - span: key.span(), - value: true, - }) - .into() - }); - Prop::KeyValue(KeyValueProp { key, value }) } } -impl Jsx -where - C: Comments, -{ - /// If we found required jsx directives, we returns true. - fn parse_directives(&mut self, span: Span) -> bool { - let mut found = false; - - let directives = self.comments.with_leading(span.lo, |comments| { - JsxDirectives::from_comments(&self.cm, span, comments, self.top_level_mark) - }); - - let JsxDirectives { - runtime, - import_source, - pragma, - pragma_frag, - } = directives; - - if let Some(runtime) = runtime { - found = true; - self.runtime = runtime; - } - - if let Some(import_source) = import_source { - found = true; - self.import_source = import_source; - } - - if let Some(pragma) = pragma { - if let Runtime::Automatic = self.runtime { - HANDLER.with(|handler| { - handler - .struct_span_err( - pragma.span(), - "pragma cannot be set when runtime is automatic", - ) - .emit() - }); - } - - found = true; - self.pragma = pragma; - } - - if let Some(pragma_frag) = pragma_frag { - if let Runtime::Automatic = self.runtime { - HANDLER.with(|handler| { - handler - .struct_span_err( - pragma_frag.span(), - "pragmaFrag cannot be set when runtime is automatic", - ) - .emit() - }); - } +#[derive(Debug, Clone, Serialize, Deserialize, Default, Merge)] +#[serde(try_from = "OptionsRaw")] +pub struct Options { + #[serde(flatten)] + pub runtime: Runtime, - found = true; - self.pragma_frag = pragma_frag; - } + #[serde(flatten)] + pub common: CommonConfig, - found - } + #[serde(default, deserialize_with = "deserialize_refresh")] + // default to disabled since this is still considered as experimental by now + pub refresh: Option, } -impl VisitMut for Jsx -where - C: Comments, -{ - noop_visit_mut_type!(); - - fn visit_mut_expr(&mut self, expr: &mut Expr) { - let top_level_node = self.top_level_node; - let mut did_work = false; +impl TryFrom<&str> for Options { + type Error = String; - if let Expr::JSXElement(el) = expr { - did_work = true; - //
=> React.createElement('div', null); - *expr = self.jsx_elem_to_expr(*el.take()); - } else if let Expr::JSXFragment(frag) = expr { - // <> => React.createElement(React.Fragment, null); - did_work = true; - *expr = self.jsx_frag_to_expr(frag.take()); - } else if let Expr::Paren(ParenExpr { - expr: inner_expr, .. - }) = expr - { - if let Expr::JSXElement(el) = &mut **inner_expr { - did_work = true; - *expr = self.jsx_elem_to_expr(*el.take()); - } else if let Expr::JSXFragment(frag) = &mut **inner_expr { - // <> => React.createElement(React.Fragment, null); - did_work = true; - *expr = self.jsx_frag_to_expr(frag.take()); - } - } - - if did_work { - self.top_level_node = false; - } - - expr.visit_mut_children_with(self); - - self.top_level_node = top_level_node; - } - - fn visit_mut_module(&mut self, module: &mut Module) { - self.parse_directives(module.span); - - for item in &module.body { - let span = item.span(); - if self.parse_directives(span) { - break; - } - } - - module.visit_mut_children_with(self); - - if self.runtime == Runtime::Automatic { - self.inject_runtime(&mut module.body, |imports, src, stmts| { - let specifiers = imports - .into_iter() - .map(|(local, imported)| { - ImportSpecifier::Named(ImportNamedSpecifier { - span: DUMMY_SP, - local, - imported: Some(ModuleExportName::Ident(imported.into())), - is_type_only: false, - }) - }) - .collect(); - - prepend_stmt( - stmts, - ImportDecl { - span: DUMMY_SP, - specifiers, - src: Str { - span: DUMMY_SP, - raw: None, - value: src.into(), - } - .into(), - type_only: Default::default(), - with: Default::default(), - phase: Default::default(), - } - .into(), - ) - }); + fn try_from(s: &str) -> Result { + match s { + "react" => Ok(Options { + runtime: Runtime::Classic(ClassicConfig::default()), + common: CommonConfig::default(), + refresh: None, + }), + "react-jsx" => Ok(Options { + runtime: Runtime::Automatic(AutomaticConfig::default()), + common: CommonConfig::default(), + refresh: None, + }), + "react-jsxdev" => Ok(Options { + runtime: Runtime::Automatic(AutomaticConfig::default()), + common: CommonConfig { + development: true.into(), + ..CommonConfig::default() + }, + refresh: None, + }), + "preserve" | "react-native" => Ok(Options { + runtime: Runtime::Preserve, + common: CommonConfig::default(), + refresh: None, + }), + other => Err(format!( + "unknown preset `{other}`, expected one of `react`, `react-jsx`, `react-jsxdev`, \ + `preserve`, `react-native`" + )), } } +} - fn visit_mut_script(&mut self, script: &mut Script) { - self.parse_directives(script.span); - - for item in &script.body { - let span = item.span(); - if self.parse_directives(span) { - break; - } - } - - script.visit_mut_children_with(self); - - if self.runtime == Runtime::Automatic { - let mark = self.unresolved_mark; - self.inject_runtime(&mut script.body, |imports, src, stmts| { - prepend_stmt(stmts, add_require(imports, src, mark)) - }); - } - } +#[derive(Deserialize)] +#[serde(untagged)] +enum OptionsRaw { + Preset(String), + Object { + #[serde(flatten)] + runtime: Runtime, + #[serde(flatten)] + common: CommonConfig, + #[serde(default, deserialize_with = "deserialize_refresh")] + refresh: Option, + }, } -// const { createElement } = require('react') -// const { jsx: jsx } = require('react/jsx-runtime') -fn add_require(imports: Vec<(Ident, IdentName)>, src: &str, unresolved_mark: Mark) -> Stmt { - VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Const, - declare: false, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: Pat::Object(ObjectPat { - span: DUMMY_SP, - props: imports - .into_iter() - .map(|(local, imported)| { - if imported.sym != local.sym { - ObjectPatProp::KeyValue(KeyValuePatProp { - key: PropName::Ident(imported), - value: Box::new(Pat::Ident(local.into())), - }) - } else { - ObjectPatProp::Assign(AssignPatProp { - span: DUMMY_SP, - key: local.into(), - value: None, - }) - } - }) - .collect(), - optional: false, - type_ann: None, +impl TryFrom for Options { + type Error = String; + + fn try_from(raw: OptionsRaw) -> Result { + match raw { + OptionsRaw::Preset(preset) => preset.as_str().try_into(), + OptionsRaw::Object { + runtime, + common, + refresh, + } => Ok(Options { + runtime, + common, + refresh, }), - // require('react') - init: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: Callee::Expr(Box::new(Expr::Ident(Ident { - ctxt: SyntaxContext::empty().apply_mark(unresolved_mark), - sym: atom!("require"), - optional: false, - ..Default::default() - }))), - args: vec![ExprOrSpread { - spread: None, - expr: Box::new(Expr::Lit(Lit::Str(Str { - span: DUMMY_SP, - value: src.into(), - raw: None, - }))), - }], - ..Default::default() - }))), - definite: false, - }], - ..Default::default() + } } - .into() } -impl Jsx -where - C: Comments, -{ - fn jsx_name(&self, name: JSXElementName) -> Box { - let span = name.span(); - match name { - JSXElementName::Ident(i) => { - if i.sym == "this" { - return ThisExpr { span }.into(); - } - - // If it starts with lowercase - if i.as_ref().starts_with(|c: char| c.is_ascii_lowercase()) { - Lit::Str(Str { - span, - raw: None, - value: i.sym, - }) - .into() - } else { - i.into() - } - } - JSXElementName::JSXNamespacedName(JSXNamespacedName { - ref ns, ref name, .. - }) => { - if self.throw_if_namespace { - HANDLER.with(|handler| { - handler - .struct_span_err( - span, - "JSX Namespace is disabled by default because react does not \ - support it yet. You can specify \ - jsc.transform.react.throwIfNamespace to false to override \ - default behavior", - ) - .emit() - }); - } - - let value = format!("{}:{}", ns.sym, name.sym); - - Lit::Str(Str { - span, - raw: None, - value: value.into(), - }) - .into() - } - JSXElementName::JSXMemberExpr(JSXMemberExpr { obj, prop, .. }) => { - fn convert_obj(obj: JSXObject) -> Box { - let span = obj.span(); +#[cfg(feature = "concurrent")] +macro_rules! static_str { + ($s:expr) => {{ + static VAL: Lazy = Lazy::new(|| $s.into()); + VAL.clone() + }}; +} - (match obj { - JSXObject::Ident(i) => { - if i.sym == "this" { - Expr::This(ThisExpr { span }) - } else { - i.into() - } - } - JSXObject::JSXMemberExpr(e) => MemberExpr { - span, - obj: convert_obj(e.obj), - prop: MemberProp::Ident(e.prop), - } - .into(), - }) - .into() - } - MemberExpr { - span, - obj: convert_obj(obj), - prop: MemberProp::Ident(prop), - } - .into() - } - } - } +#[cfg(not(feature = "concurrent"))] +macro_rules! static_str { + ($s:expr) => { + $s.into() + }; } -fn to_prop_name(n: JSXAttrName) -> PropName { - let span = n.span(); +pub fn default_import_source() -> Atom { + atom!("react") +} - match n { - JSXAttrName::Ident(i) => { - if i.sym.contains('-') { - PropName::Str(Str { - span, - raw: None, - value: i.sym, - }) - } else { - PropName::Ident(i) - } - } - JSXAttrName::JSXNamespacedName(JSXNamespacedName { ns, name, .. }) => { - let value = format!("{}:{}", ns.sym, name.sym); +pub fn default_pragma() -> BytesStr { + static_str!("React.createElement") +} - PropName::Str(Str { - span, - raw: None, - value: value.into(), - }) - } - } +pub fn default_pragma_frag() -> BytesStr { + static_str!("React.Fragment") } #[inline] -fn jsx_text_to_str(t: Atom) -> Atom { +pub(crate) fn jsx_text_to_str(t: Atom) -> Atom { let mut buf = String::new(); let replaced = t.replace('\t', " "); @@ -1407,48 +282,42 @@ fn jsx_text_to_str(t: Atom) -> Atom { buf.into() } -fn jsx_attr_value_to_expr(v: JSXAttrValue) -> Option> { - Some(match v { - JSXAttrValue::Lit(Lit::Str(s)) => { - let value = transform_jsx_attr_str(&s.value); - - Lit::Str(Str { - span: s.span, - raw: None, - value: value.into(), - }) - .into() - } - JSXAttrValue::Lit(lit) => Box::new(lit.into()), - JSXAttrValue::JSXExprContainer(e) => match e.expr { - JSXExpr::JSXEmptyExpr(_) => None?, - JSXExpr::Expr(e) => e, - }, - JSXAttrValue::JSXElement(e) => e.into(), - JSXAttrValue::JSXFragment(f) => f.into(), - }) -} - -fn count_children(children: &[JSXElementChild]) -> usize { - children - .iter() - .filter(|v| match v { - JSXElementChild::JSXText(text) => { - let text = jsx_text_to_str(text.value.clone()); - !text.is_empty() - } - JSXElementChild::JSXExprContainer(e) => match e.expr { - JSXExpr::JSXEmptyExpr(_) => false, - JSXExpr::Expr(_) => true, - }, - JSXElementChild::JSXSpreadChild(_) => true, - JSXElementChild::JSXElement(_) => true, - JSXElementChild::JSXFragment(_) => true, - }) - .count() +pub fn jsx( + cm: swc_common::sync::Lrc, + comments: Option, + mut options: Options, + unresolved_mark: swc_common::Mark, +) -> (impl swc_ecma_ast::Pass, impl swc_ecma_ast::Pass) +where + C: swc_common::comments::Comments + Clone + 'static, +{ + options.runtime = parse_directives(options.runtime, comments.clone()); + + let Options { + runtime, common, .. + } = options; + + match runtime { + Runtime::Automatic(config) => ( + None, + Some(automatic( + config, + common, + unresolved_mark, + comments.clone(), + cm.clone(), + )), + ), + Runtime::Classic(config) => ( + Some(classic(config, common, comments.clone(), cm.clone())), + None, + ), + Runtime::Preserve => (None, None), + } } -fn transform_jsx_attr_str(v: &str) -> String { +/// Transform JSX attribute string by handling escape sequences and whitespace +pub(crate) fn transform_jsx_attr_str(v: &str) -> String { let single_quote = false; let mut buf = String::with_capacity(v.len()); let mut iter = v.chars().peekable(); @@ -1492,3 +361,80 @@ fn transform_jsx_attr_str(v: &str) -> String { buf } + +/// Convert JSX element name to expression +pub(crate) fn jsx_name(name: JSXElementName, throw_if_namespace: bool) -> Box { + let span = name.span(); + match name { + JSXElementName::Ident(i) => { + if i.sym == "this" { + return ThisExpr { span }.into(); + } + + // If it starts with lowercase + if i.as_ref().starts_with(|c: char| c.is_ascii_lowercase()) { + Lit::Str(Str { + span, + raw: None, + value: i.sym, + }) + .into() + } else { + i.into() + } + } + JSXElementName::JSXNamespacedName(JSXNamespacedName { + ref ns, ref name, .. + }) => { + if throw_if_namespace { + swc_common::errors::HANDLER.with(|handler| { + handler + .struct_span_err( + span, + "JSX Namespace is disabled by default because react does not support \ + it yet. You can specify jsc.transform.react.throwIfNamespace to \ + false to override default behavior", + ) + .emit() + }); + } + + let value = format!("{}:{}", ns.sym, name.sym); + + Lit::Str(Str { + span, + raw: None, + value: value.into(), + }) + .into() + } + JSXElementName::JSXMemberExpr(JSXMemberExpr { obj, prop, .. }) => { + fn convert_obj(obj: JSXObject) -> Box { + let span = obj.span(); + + (match obj { + JSXObject::Ident(i) => { + if i.sym == "this" { + Expr::This(ThisExpr { span }) + } else { + i.into() + } + } + JSXObject::JSXMemberExpr(e) => MemberExpr { + span, + obj: convert_obj(e.obj), + prop: MemberProp::Ident(e.prop), + } + .into(), + }) + .into() + } + MemberExpr { + span, + obj: convert_obj(obj), + prop: MemberProp::Ident(prop), + } + .into() + } + } +} diff --git a/crates/swc_ecma_transforms_react/src/jsx/parse_directives.rs b/crates/swc_ecma_transforms_react/src/jsx/parse_directives.rs new file mode 100644 index 000000000000..6dce6543e72b --- /dev/null +++ b/crates/swc_ecma_transforms_react/src/jsx/parse_directives.rs @@ -0,0 +1,160 @@ +use std::mem; + +use bytes_str::BytesStr; +use memchr::memmem; +use swc_common::comments::Comments; + +use crate::{AutomaticConfig, ClassicConfig, Runtime}; + +#[derive(Debug)] +enum JSXRuntime { + Automatic, + Classic, +} + +pub fn parse_directives(mut runtime: Runtime, comments: Option) -> Runtime +where + C: Comments + Clone, +{ + let Some(comments) = comments else { + return runtime; + }; + + let mut jsx_runtime; + let mut import_source = (None, 0u32); + let mut pragma = (None, 0u32); + let mut pragma_frag = (None, 0u32); + + match &mut runtime { + Runtime::Automatic(config) => { + jsx_runtime = (JSXRuntime::Automatic, 0); + import_source = (Some(mem::take(&mut config.import_source)), 0); + } + Runtime::Classic(ref mut config) => { + jsx_runtime = (JSXRuntime::Classic, 0); + pragma = (Some(mem::take(&mut config.pragma)), 0); + pragma_frag = (Some(mem::take(&mut config.pragma_frag)), 0); + } + Runtime::Preserve => return runtime, + }; + + comments.for_each(&mut |comment| { + let start = comment.span.lo.0; + let bytes = comment.text.as_bytes(); + // jsxRuntime + // jsxImportSource + // jsxFrag + // jsx + let it = memmem::find_iter(bytes, b"@jsx"); + for offset in it { + let pos = start + offset as u32; + let Some(b) = bytes.get(offset + 4) else { + continue; + }; + + match b { + b'R' => { + if bytes.get((offset + 5)..(offset + 11)) == Some(b"untime") { + // @jsxRuntime + if pos < jsx_runtime.1 { + continue; + } + + if let Some(value) = extract_value(bytes, offset + 11) { + jsx_runtime = match value { + "automatic" => (JSXRuntime::Automatic, pos), + "classic" => (JSXRuntime::Classic, pos), + _ => continue, + }; + } + } + } + b'I' => { + if bytes.get((offset + 5)..(offset + 12)) == Some(b"mportSource") { + // @jsxImportSource + if pos < import_source.1 { + continue; + } + + if let Some(value) = extract_value(bytes, offset + 12) { + import_source = (Some(value.into()), pos); + } + } + } + b'F' => { + if bytes.get((offset + 5)..(offset + 8)) == Some(b"rag") { + // @jsxFrag + if pos < pragma_frag.1 { + continue; + } + + if let Some(value) = extract_value(bytes, offset + 8) { + pragma_frag = (Some(BytesStr::from_str_slice(value)), pos); + } + } + } + b if is_ascii_whitespace_sameline(*b) => { + // @jsx + if pos < jsx_runtime.1 { + continue; + } + + if let Some(value) = extract_value(bytes, offset + 4) { + pragma = (Some(BytesStr::from_str_slice(value)), pos); + } + } + _ => {} + } + } + }); + + match jsx_runtime.0 { + JSXRuntime::Automatic => Runtime::Automatic(AutomaticConfig { + import_source: import_source.0.unwrap_or_else(|| "react".into()), + }), + JSXRuntime::Classic => Runtime::Classic(ClassicConfig { + pragma: pragma.0.unwrap_or_else(|| "React.createElement".into()), + pragma_frag: pragma_frag.0.unwrap_or_else(|| "React.Fragment".into()), + }), + } +} + +fn extract_value(bytes: &[u8], start_offset: usize) -> Option<&str> { + if !is_ascii_whitespace_sameline(bytes[start_offset]) { + return None; + } + + // Skip whitespace after the pragma name + let mut offset = start_offset; + while let Some(&b) = bytes.get(offset) { + if is_ascii_whitespace_sameline(b) { + offset += 1; + } else { + break; + } + } + + // Find the start of the value + let value_start = offset; + + // Find the end of the value (until whitespace, newline, or end of comment) + while let Some(&b) = bytes.get(offset) { + if is_ascii_whitespace_sameline(b) { + break; + } + offset += 1; + } + + let value_end = offset; + + if value_start < value_end { + std::str::from_utf8(&bytes[value_start..value_end]).ok() + } else { + None + } +} + +#[inline(always)] +fn is_ascii_whitespace_sameline(c: u8) -> bool { + matches!(c, b'\t' | b'\x0C' | b' ') +} diff --git a/crates/swc_ecma_transforms_react/src/jsx/static_check.rs b/crates/swc_ecma_transforms_react/src/jsx/static_check.rs index a1f6221f361a..557cdf88eef2 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/static_check.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/static_check.rs @@ -6,22 +6,19 @@ use swc_ecma_ast::*; /// step while we deprecate key spread from props. Afterwards, /// we will stop using createElement in the transform. pub(super) fn should_use_create_element(attrs: &[JSXAttrOrSpread]) -> bool { - let mut seen_prop_spread = false; + let mut seen_spread = false; for attr in attrs { - if seen_prop_spread - && match attr { - JSXAttrOrSpread::JSXAttr(attr) => match &attr.name { - JSXAttrName::Ident(i) => i.sym == "key", - JSXAttrName::JSXNamespacedName(_) => false, - }, - _ => false, + match attr { + JSXAttrOrSpread::JSXAttr(JSXAttr { + name: JSXAttrName::Ident(IdentName { sym, .. }), + .. + }) if seen_spread && sym == "key" => { + return true; } - { - return true; - } - - if let JSXAttrOrSpread::SpreadElement(_) = attr { - seen_prop_spread = true; + JSXAttrOrSpread::SpreadElement(..) => { + seen_spread = true; + } + _ => {} } } diff --git a/crates/swc_ecma_transforms_react/src/jsx/tests.rs b/crates/swc_ecma_transforms_react/src/jsx/tests.rs index ee4a2239db5c..6a6e95364666 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/tests.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/tests.rs @@ -5,8 +5,10 @@ use std::{ path::{Path, PathBuf}, }; +use swc_common::{FileName, Mark}; +use swc_ecma_ast::*; use swc_ecma_codegen::{Config, Emitter}; -use swc_ecma_parser::{EsSyntax, Parser, StringInput}; +use swc_ecma_parser::{EsSyntax, Parser, StringInput, Syntax}; use swc_ecma_transforms_base::{fixer::fixer, hygiene, resolver}; use swc_ecma_transforms_compat::{ es2015::{arrow, classes}, @@ -21,15 +23,17 @@ use crate::{display_name, pure_annotations, react}; fn tr(t: &mut Tester, options: Options, top_level_mark: Mark) -> impl Pass { let unresolved_mark = Mark::new(); + let (before_resolver_jsx, after_resolver_jsx) = jsx( + t.cm.clone(), + Some(t.comments.clone()), + options, + unresolved_mark, + ); + ( + before_resolver_jsx, resolver(unresolved_mark, top_level_mark, false), - jsx( - t.cm.clone(), - Some(t.comments.clone()), - options, - top_level_mark, - unresolved_mark, - ), + after_resolver_jsx, display_name(), classes(Default::default()), arrow(unresolved_mark), @@ -38,9 +42,18 @@ fn tr(t: &mut Tester, options: Options, top_level_mark: Mark) -> impl Pass { #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] +#[serde(rename_all = "camelCase")] struct FixtureOptions { - #[serde(flatten)] - options: Options, + runtime: Option, + + #[serde(default)] + pragma: Option, + + #[serde(default)] + pragma_frag: Option, + + #[serde(default)] + import_source: Option, #[serde(default, rename = "BABEL_8_BREAKING")] babel_8_breaking: bool, @@ -51,6 +64,12 @@ struct FixtureOptions { #[serde(default)] throws: Option, + #[serde(default)] + pub development: bool, + + #[serde(default = "true_by_default")] + pub throw_if_namespace: bool, + #[serde(default, alias = "useBuiltIns")] use_builtins: bool, } @@ -59,46 +78,78 @@ fn true_by_default() -> bool { true } -fn fixture_tr(t: &mut Tester, mut options: FixtureOptions) -> impl Pass { +impl From for Options { + fn from(val: FixtureOptions) -> Self { + let runtime = match val.runtime.as_deref() { + Some("automatic") => Runtime::Automatic(AutomaticConfig { + import_source: val + .import_source + .map(Into::into) + .unwrap_or_else(default_import_source), + }), + Some("classic") => Runtime::Classic(ClassicConfig { + pragma: val.pragma.map(Into::into).unwrap_or_else(default_pragma), + pragma_frag: val + .pragma_frag + .map(Into::into) + .unwrap_or_else(default_pragma_frag), + }), + Some("preserve") => Runtime::Preserve, + _ => { + if val.babel_8_breaking { + Runtime::Automatic(Default::default()) + } else { + Runtime::Classic(Default::default()) + } + } + }; + + Options { + runtime, + common: CommonConfig { + development: val.development.into(), + pure: val.pure.into(), + throw_if_namespace: val.throw_if_namespace.into(), + }, + refresh: None, + } + } +} + +fn fixture_tr(t: &mut Tester, options: FixtureOptions) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); - options.options.next = Some(options.babel_8_breaking || options.options.runtime.is_some()); + let options = options.into(); - if !options.babel_8_breaking && options.options.runtime.is_none() { - options.options.runtime = Some(Runtime::Classic); - } + let (before_resolver_jsx, after_resolver_jsx) = jsx( + t.cm.clone(), + Some(t.comments.clone()), + options, + unresolved_mark, + ); ( + before_resolver_jsx, resolver(unresolved_mark, top_level_mark, false), - jsx( - t.cm.clone(), - Some(t.comments.clone()), - options.options, - top_level_mark, - unresolved_mark, - ), + after_resolver_jsx, display_name(), pure_annotations(Some(t.comments.clone())), ) } -fn integration_tr(t: &mut Tester, mut options: FixtureOptions) -> impl Pass { +fn integration_tr(t: &mut Tester, options: FixtureOptions) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); - options.options.next = Some(options.babel_8_breaking || options.options.runtime.is_some()); - - if !options.babel_8_breaking && options.options.runtime.is_none() { - options.options.runtime = Some(Runtime::Classic); - } + let options = options.into(); ( resolver(unresolved_mark, top_level_mark, false), react( t.cm.clone(), Some(t.comments.clone()), - options.options, + options, top_level_mark, unresolved_mark, ), @@ -337,7 +388,10 @@ test!( |t| tr( t, Options { - pragma: Some("dom".into()), + runtime: Runtime::Classic(ClassicConfig { + pragma: "dom".into(), + ..Default::default() + }), ..Default::default() }, Mark::fresh(Mark::root()) @@ -808,8 +862,14 @@ test!( |t| tr( t, Options { - pragma: Some("h".into()), - throw_if_namespace: false.into(), + runtime: Runtime::Classic(ClassicConfig { + pragma: "h".into(), + ..Default::default() + }), + common: CommonConfig { + throw_if_namespace: false.into(), + ..Default::default() + }, ..Default::default() }, Mark::fresh(Mark::root()) @@ -981,7 +1041,7 @@ test!( ..Default::default() }), |t| { - let top_level_mark = Mark::fresh(Mark::root()); + let _top_level_mark = Mark::fresh(Mark::root()); let unresolved_mark = Mark::fresh(Mark::root()); ( @@ -990,7 +1050,6 @@ test!( t.cm.clone(), Some(t.comments.clone()), Default::default(), - top_level_mark, unresolved_mark, ), ) @@ -1026,15 +1085,17 @@ test!( let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); + let (before_resolver_jsx, after_resolver_jsx) = jsx( + t.cm.clone(), + Some(t.comments.clone()), + Default::default(), + unresolved_mark, + ); + ( + before_resolver_jsx, resolver(unresolved_mark, top_level_mark, false), - jsx( - t.cm.clone(), - Some(t.comments.clone()), - Default::default(), - top_level_mark, - unresolved_mark, - ), + after_resolver_jsx, ) }, issue_4956, @@ -1128,7 +1189,7 @@ fn test_script(src: &str, output: &Path, options: Options) { resolver(Mark::new(), top_level_mark, false), react( tester.cm.clone(), - Some(&tester.comments), + Some(tester.comments.clone()), options, top_level_mark, unresolved_mark, diff --git a/crates/swc_ecma_transforms_react/src/jsx_self/mod.rs b/crates/swc_ecma_transforms_react/src/jsx_self/mod.rs deleted file mode 100644 index 0ff43babd533..000000000000 --- a/crates/swc_ecma_transforms_react/src/jsx_self/mod.rs +++ /dev/null @@ -1,106 +0,0 @@ -use swc_common::DUMMY_SP; -use swc_ecma_ast::*; -use swc_ecma_transforms_base::perf::Parallel; -use swc_ecma_utils::quote_ident; -use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; - -#[cfg(test)] -mod tests; - -/// `@babel/plugin-transform-react-jsx-self` -/// -/// Add a __self prop to all JSX Elements -pub fn jsx_self(dev: bool) -> impl Pass { - visit_mut_pass(JsxSelf { - dev, - ctx: Default::default(), - }) -} - -/// See -#[derive(Clone, Copy, Default)] -struct Context { - in_constructor: bool, - in_derived_class: bool, -} - -#[derive(Clone, Copy)] -struct JsxSelf { - dev: bool, - ctx: Context, -} - -impl JsxSelf { - fn with_in_constructor>(&mut self, in_constructor: bool, n: &mut N) { - let old = self.ctx; - self.ctx.in_constructor = in_constructor; - n.visit_mut_children_with(self); - self.ctx = old; - } -} - -impl Parallel for JsxSelf { - fn create(&self) -> Self { - *self - } - - fn merge(&mut self, _: Self) {} -} - -impl VisitMut for JsxSelf { - noop_visit_mut_type!(); - - fn visit_mut_class(&mut self, n: &mut Class) { - let old = self.ctx; - self.ctx.in_derived_class = n.super_class.is_some(); - n.visit_mut_children_with(self); - self.ctx = old; - } - - fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) { - self.with_in_constructor(false, n); - } - - fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) { - self.with_in_constructor(false, n); - } - - fn visit_mut_prop(&mut self, n: &mut Prop) { - match n { - Prop::Getter(_) | Prop::Setter(_) | Prop::Method(_) => { - self.with_in_constructor(false, n) - } - _ => n.visit_mut_children_with(self), - } - } - - fn visit_mut_class_member(&mut self, n: &mut ClassMember) { - match n { - ClassMember::Constructor(_) => self.with_in_constructor(true, n), - ClassMember::Method(_) - | ClassMember::PrivateMethod(_) - | ClassMember::StaticBlock(_) => self.with_in_constructor(false, n), - _ => n.visit_mut_children_with(self), - } - } - - fn visit_mut_jsx_opening_element(&mut self, n: &mut JSXOpeningElement) { - if !self.dev { - return; - } - - // https://github.com/babel/babel/blob/1bdb1a4175ed1fc40751fb84dc4ad1900260f28f/packages/babel-plugin-transform-react-jsx-self/src/index.ts#L50 - if self.ctx.in_constructor && self.ctx.in_derived_class { - return; - } - - n.attrs.push(JSXAttrOrSpread::JSXAttr(JSXAttr { - span: DUMMY_SP, - name: JSXAttrName::Ident(quote_ident!("__self")), - value: Some(JSXAttrValue::JSXExprContainer(JSXExprContainer { - span: DUMMY_SP, - expr: JSXExpr::Expr(Box::new(ThisExpr { span: DUMMY_SP }.into())), - })), - })); - } -} diff --git a/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs b/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs deleted file mode 100644 index 62f23db76a4c..000000000000 --- a/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs +++ /dev/null @@ -1,107 +0,0 @@ -use swc_common::Mark; -use swc_ecma_transforms_base::resolver; -use swc_ecma_transforms_compat::es2015::arrow; -use swc_ecma_transforms_testing::test; - -use super::*; - -fn tr() -> impl Pass { - jsx_self(true) -} - -test!( - module, - ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { - jsx: true, - ..Default::default() - }), - |_| tr(), - basic_sample, - r#"var x = "# -); - -test!( - module, - ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { - jsx: true, - ..Default::default() - }), - |_| tr(), - disable_with_super, - r#"class A { } - -class B extends A { - constructor() { - ; - super(); - ; - } -} - -class C { - constructor() { - ; - class D extends A { - constructor() { - super(); - } - } - const E = class extends A { - constructor() { - super(); - } - }; - } -} - -class E extends A { - constructor() { - this.x = () => ; - this.y = function () { - return ; - }; - function z() { - return ; - } - { } - super(); - } -} - -class F { - constructor() { - - } -} - -class G extends A { - constructor() { - return ; - } -}"# -); - -test!( - module, - ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { - jsx: true, - ..Default::default() - }), - |_| { - let unresolved_mark = Mark::new(); - let top_level_mark = Mark::new(); - ( - resolver(unresolved_mark, top_level_mark, false), - tr(), - arrow(unresolved_mark), - ) - }, - arrow_function, - r#"
; -() =>
; - -function fn() { -
; - () =>
; -}"# -); diff --git a/crates/swc_ecma_transforms_react/src/jsx_src/mod.rs b/crates/swc_ecma_transforms_react/src/jsx_src/mod.rs deleted file mode 100644 index 615cfb194d29..000000000000 --- a/crates/swc_ecma_transforms_react/src/jsx_src/mod.rs +++ /dev/null @@ -1,74 +0,0 @@ -use swc_common::{sync::Lrc, SourceMap, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_transforms_base::perf::Parallel; -use swc_ecma_utils::quote_ident; -use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; - -#[cfg(test)] -mod tests; - -/// `@babel/plugin-transform-react-jsx-source` -pub fn jsx_src(dev: bool, cm: Lrc) -> impl Pass { - visit_mut_pass(JsxSrc { cm, dev }) -} - -#[derive(Clone)] -struct JsxSrc { - cm: Lrc, - dev: bool, -} - -impl Parallel for JsxSrc { - fn create(&self) -> Self { - self.clone() - } - - fn merge(&mut self, _: Self) {} -} - -impl VisitMut for JsxSrc { - noop_visit_mut_type!(); - - fn visit_mut_jsx_opening_element(&mut self, e: &mut JSXOpeningElement) { - if !self.dev || e.span == DUMMY_SP { - return; - } - - e.visit_mut_children_with(self); - - let loc = self.cm.lookup_char_pos(e.span.lo); - let file_name = loc.file.name.to_string(); - - e.attrs.push(JSXAttrOrSpread::JSXAttr(JSXAttr { - span: DUMMY_SP, - name: JSXAttrName::Ident(quote_ident!("__source")), - value: Some(JSXAttrValue::JSXExprContainer(JSXExprContainer { - span: DUMMY_SP, - expr: JSXExpr::Expr(Box::new( - ObjectLit { - span: DUMMY_SP, - props: vec![ - PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("fileName")), - value: Box::new(Expr::Lit(Lit::Str(Str { - span: DUMMY_SP, - raw: None, - value: file_name.into(), - }))), - }))), - PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("lineNumber")), - value: loc.line.into(), - }))), - PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(quote_ident!("columnNumber")), - value: (loc.col.0 + 1).into(), - }))), - ], - } - .into(), - )), - })), - })); - } -} diff --git a/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs b/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs deleted file mode 100644 index 79e24b9e50d3..000000000000 --- a/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs +++ /dev/null @@ -1,66 +0,0 @@ -use swc_common::FilePathMapping; -use swc_ecma_transforms_testing::{test, test_exec}; - -use super::*; - -fn tr() -> impl Pass { - let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - jsx_src(true, cm) -} - -test_exec!( - ignore, - ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { - jsx: true, - ..Default::default() - }), - |_| tr(), - basic_sample, - r#" -var actual = transform( - 'var x = ', - Object.assign({}, opts, { filename: '/fake/path/mock.js' }) -).code; - -var expected = multiline([ - 'var _jsxFileName = "/fake/path/mock.js";', - 'var x = ;', -]); - -expect(actual).toBe(expected); -"# -); - -test!( - module, - ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { - jsx: true, - ..Default::default() - }), - |_| tr(), - no_jsx, - r#"var x = 42;"# -); - -test_exec!( - ignore, - ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { - jsx: true, - ..Default::default() - }), - |_| tr(), - with_source, - r#" -var actual = transform( - 'var x = ;', - Object.assign({}, opts, { filename: '/fake/path/mock.js' }) -).code; - -var expected = 'var x = ;'; - -expect(actual).toBe(expected); -"# -); diff --git a/crates/swc_ecma_transforms_react/src/lib.rs b/crates/swc_ecma_transforms_react/src/lib.rs index dfd5b4184f3a..efeabca3cb00 100644 --- a/crates/swc_ecma_transforms_react/src/lib.rs +++ b/crates/swc_ecma_transforms_react/src/lib.rs @@ -4,22 +4,20 @@ #![allow(rustc::untranslatable_diagnostic_trivial)] #![cfg_attr(not(feature = "concurrent"), allow(unused))] +use std::mem; + use swc_common::{comments::Comments, sync::Lrc, Mark, SourceMap}; use swc_ecma_ast::Pass; pub use self::{ display_name::display_name, jsx::*, - jsx_self::jsx_self, - jsx_src::jsx_src, pure_annotations::pure_annotations, refresh::{options::RefreshOptions, refresh}, }; mod display_name; mod jsx; -mod jsx_self; -mod jsx_src; mod pure_annotations; mod refresh; @@ -39,36 +37,46 @@ mod refresh; pub fn react( cm: Lrc, comments: Option, - mut options: Options, + options: Options, top_level_mark: Mark, unresolved_mark: Mark, -) -> impl Pass +) -> (impl Pass, impl Pass) where - C: Comments + Clone, + C: Comments + Clone + 'static, { - let Options { development, .. } = options; - let development = development.unwrap_or(false); + let development = options.common.development.into_bool(); + + let (auto_config, classic_config) = match parse_directives(options.runtime, comments.clone()) { + Runtime::Automatic(ref mut config) => (Some(mem::take(config)), None), + Runtime::Classic(ref mut config) => (None, Some(mem::take(config))), + Runtime::Preserve => (None, None), + }; - let refresh_options = options.refresh.take(); + let refresh_options = options.refresh; - ( - jsx_src(development, cm.clone()), - jsx_self(development), + let before_resolver = + classic_config.map(|config| classic(config, options.common, comments.clone(), cm.clone())); + + let after_resolver = ( refresh( development, - refresh_options.clone(), - cm.clone(), - comments.clone(), - top_level_mark, - ), - jsx( + refresh_options, cm.clone(), comments.clone(), - options, top_level_mark, - unresolved_mark, ), + auto_config.map(|config| { + automatic( + config, + options.common, + unresolved_mark, + comments.clone(), + cm.clone(), + ) + }), display_name(), pure_annotations(comments.clone()), - ) + ); + + (before_resolver, after_resolver) } diff --git a/crates/swc_ecma_transforms_react/src/pure_annotations/mod.rs b/crates/swc_ecma_transforms_react/src/pure_annotations/mod.rs index 98fc33b81143..c8f733c576fc 100644 --- a/crates/swc_ecma_transforms_react/src/pure_annotations/mod.rs +++ b/crates/swc_ecma_transforms_react/src/pure_annotations/mod.rs @@ -1,6 +1,6 @@ use rustc_hash::FxHashMap; use swc_atoms::{atom, Atom}; -use swc_common::{comments::Comments, Span}; +use swc_common::{comments::Comments, Span, Spanned}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; @@ -109,7 +109,7 @@ where _ => false, }; - if is_react_call { + if is_react_call && !(call.span.is_pure() || call.callee.span().is_pure()) { if let Some(comments) = &self.comments { if call.span.lo.is_dummy() { call.span.lo = Span::dummy_with_cmt().lo; diff --git a/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs b/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs index 99c3c4f36d8b..8b9b7dc2100d 100644 --- a/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs +++ b/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs @@ -66,15 +66,19 @@ fn run_test(input: &str, expected: &str) { let top_level_mark = Mark::new(); let (actual, actual_sm, actual_comments) = parse(tester, input)?; + + let (before_resolver, after_resolver) = crate::react( + actual_sm.clone(), + Some(actual_comments.clone()), + Default::default(), + top_level_mark, + unresolved_mark, + ); + let actual = actual + .apply(before_resolver) .apply(&mut resolver(unresolved_mark, top_level_mark, false)) - .apply(&mut crate::react( - actual_sm.clone(), - Some(&actual_comments), - Default::default(), - top_level_mark, - unresolved_mark, - )); + .apply(after_resolver); let actual_src = emit(actual_sm, actual_comments, &actual); @@ -131,10 +135,12 @@ test!( test!( create_element_jsx, r#" + // @jsxRuntime classic import React from 'react'; const x =
; "#, r#" + // @jsxRuntime classic import React from 'react'; const x = /*#__PURE__*/ React.createElement("div", null); "# @@ -143,10 +149,12 @@ test!( test!( create_element_fragment_jsx, r#" + // @jsxRuntime classic import React from 'react'; const x = <>
; "#, r#" + // @jsxRuntime classic import React from 'react'; const x = /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("div", null)); "# diff --git a/crates/swc_ecma_transforms_react/src/refresh/tests.rs b/crates/swc_ecma_transforms_react/src/refresh/tests.rs index 6c02b74eaffe..f7f92e92c94c 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/tests.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/tests.rs @@ -568,7 +568,15 @@ test!( let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); + let (before_resolver_jsx, after_resolver_jsx) = jsx( + t.cm.clone(), + Some(t.comments.clone()), + Default::default(), + unresolved_mark, + ); + ( + before_resolver_jsx, resolver(unresolved_mark, top_level_mark, false), refresh( true, @@ -580,13 +588,7 @@ test!( Some(t.comments.clone()), top_level_mark, ), - jsx( - t.cm.clone(), - Some(t.comments.clone()), - Default::default(), - top_level_mark, - unresolved_mark, - ), + after_resolver_jsx, ) }, include_hook_signature_in_commonjs, diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_229.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_229.js index 836115ae17e2..fad2f8dfeee3 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_229.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_229.js @@ -1,2 +1,7 @@ -const a = /*#__PURE__*/ React.createElement(React.Fragment, null, "test"); -const b = /*#__PURE__*/ React.createElement("div", null, "test"); +import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; +const a = /*#__PURE__*/ _jsx(_Fragment, { + children: "test" +}); +const b = /*#__PURE__*/ _jsx("div", { + children: "test" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_351.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_351.js index 0bb9977e8f0d..87b9c1377a49 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_351.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_351.js @@ -1,2 +1,3 @@ +import { jsx as _jsx } from "react/jsx-runtime"; import React from 'react'; -/*#__PURE__*/ React.createElement("div", null); +/*#__PURE__*/ _jsx("div", {}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_481.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_481.js index 9f004ef00c8d..dafe249f7ea1 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_481.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_481.js @@ -1 +1,7 @@ -/*#__PURE__*/ React.createElement("span", null, " ", foo); +/*#__PURE__*/ import { jsxs as _jsxs } from "react/jsx-runtime"; +_jsxs("span", { + children: [ + " ", + foo + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_4956.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_4956.js index 5a93f181786f..471257105acd 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_4956.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_4956.js @@ -1,3 +1,4 @@ -/*#__PURE__*/ React.createElement("div", { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { title: "\u2028" }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_517.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_517.js index 671fa977b19a..3fbf9f2a53ec 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_517.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_517.js @@ -1,4 +1,6 @@ +import { jsx as _jsx } from "react/jsx-runtime"; import React from 'react'; -/*#__PURE__*/ React.createElement("div", { - style: "white-space: pre" -}, "Hello World"); +/*#__PURE__*/ _jsx("div", { + style: "white-space: pre", + children: "Hello World" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_542.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_542.js index 9f4e05a237b2..21852533cb08 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_542.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/issue_542.js @@ -1 +1,10 @@ -let page = /*#__PURE__*/ React.createElement("p", null, "Click ", /*#__PURE__*/ React.createElement("em", null, "New melody"), " listen to a randomly generated melody"); +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +let page = /*#__PURE__*/ _jsxs("p", { + children: [ + "Click ", + /*#__PURE__*/ _jsx("em", { + children: "New melody" + }), + " listen to a randomly generated melody" + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_add_appropriate_newlines.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_add_appropriate_newlines.js index 474e9d8af22e..99ca50478951 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_add_appropriate_newlines.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_add_appropriate_newlines.js @@ -1,4 +1,5 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { ...props, sound: "moo" }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_arrow_functions.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_arrow_functions.js index 51f291a9b97f..067a61c28e63 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_arrow_functions.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_arrow_functions.js @@ -1,12 +1,13 @@ +import { jsx as _jsx } from "react/jsx-runtime"; var foo = function() { var _this = this; return function() { - return /*#__PURE__*/ React.createElement(_this, null); + return /*#__PURE__*/ _jsx(_this, {}); }; }; var bar = function() { var _this = this; return function() { - return /*#__PURE__*/ React.createElement(_this.foo, null); + return /*#__PURE__*/ _jsx(_this.foo, {}); }; }; diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_attribute_html_entity_quote.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_attribute_html_entity_quote.js index f7290aebbd24..66188f55e34f 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_attribute_html_entity_quote.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_attribute_html_entity_quote.js @@ -1,3 +1,4 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { text: 'Hello "World"' }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_concatenates_adjacent_string_literals.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_concatenates_adjacent_string_literals.js index a49318e35e0e..c6d88fbcc211 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_concatenates_adjacent_string_literals.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_concatenates_adjacent_string_literals.js @@ -1 +1,14 @@ -var x = /*#__PURE__*/ React.createElement("div", null, "foo", "bar", "baz", /*#__PURE__*/ React.createElement("div", null, "buz bang"), "qux", null, "quack"); +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsxs("div", { + children: [ + "foo", + "bar", + "baz", + /*#__PURE__*/ _jsx("div", { + children: "buz bang" + }), + "qux", + null, + "quack" + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_dont_coerce_expression_containers.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_dont_coerce_expression_containers.js index c6a480aa25f7..cc63292453b9 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_dont_coerce_expression_containers.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_dont_coerce_expression_containers.js @@ -1 +1,8 @@ -/*#__PURE__*/ React.createElement(Text, null, "To get started, edit index.ios.js!!!", "\n", "Press Cmd+R to reload"); +/*#__PURE__*/ import { jsxs as _jsxs } from "react/jsx-runtime"; +_jsxs(Text, { + children: [ + "To get started, edit index.ios.js!!!", + "\n", + "Press Cmd+R to reload" + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment.js index 19393033e6dd..679b3a7d0bd3 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment.js @@ -1,8 +1,16 @@ -/** @jsx dom */ /*#__PURE__*/ dom(Foo, null); -var profile = /*#__PURE__*/ dom("div", null, /*#__PURE__*/ dom("img", { - src: "avatar.png", - className: "profile" -}), /*#__PURE__*/ dom("h3", null, [ - user.firstName, - user.lastName -].join(" "))); +/** @jsx dom */ /*#__PURE__*/ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +_jsx(Foo, {}); +var profile = /*#__PURE__*/ _jsxs("div", { + children: [ + /*#__PURE__*/ _jsx("img", { + src: "avatar.png", + className: "profile" + }), + /*#__PURE__*/ _jsx("h3", { + children: [ + user.firstName, + user.lastName + ].join(" ") + }) + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment_if_jsx_pragma_option_set.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment_if_jsx_pragma_option_set.js index 19393033e6dd..679b3a7d0bd3 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment_if_jsx_pragma_option_set.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_honor_custom_jsx_comment_if_jsx_pragma_option_set.js @@ -1,8 +1,16 @@ -/** @jsx dom */ /*#__PURE__*/ dom(Foo, null); -var profile = /*#__PURE__*/ dom("div", null, /*#__PURE__*/ dom("img", { - src: "avatar.png", - className: "profile" -}), /*#__PURE__*/ dom("h3", null, [ - user.firstName, - user.lastName -].join(" "))); +/** @jsx dom */ /*#__PURE__*/ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +_jsx(Foo, {}); +var profile = /*#__PURE__*/ _jsxs("div", { + children: [ + /*#__PURE__*/ _jsx("img", { + src: "avatar.png", + className: "profile" + }), + /*#__PURE__*/ _jsx("h3", { + children: [ + user.firstName, + user.lastName + ].join(" ") + }) + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_with_retainlines_option.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_with_retainlines_option.js index f3724d89eec1..958fa2797663 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_with_retainlines_option.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_with_retainlines_option.js @@ -1 +1,4 @@ -var div = /*#__PURE__*/ React.createElement("div", null, "test"); +import { jsx as _jsx } from "react/jsx-runtime"; +var div = /*#__PURE__*/ _jsx("div", { + children: "test" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_without_retainlines_option.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_without_retainlines_option.js index f3724d89eec1..958fa2797663 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_without_retainlines_option.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_jsx_without_retainlines_option.js @@ -1 +1,4 @@ -var div = /*#__PURE__*/ React.createElement("div", null, "test"); +import { jsx as _jsx } from "react/jsx-runtime"; +var div = /*#__PURE__*/ _jsx("div", { + children: "test" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_add_quotes_es3.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_add_quotes_es3.js index 55e6446feccc..97b4efbd79d2 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_add_quotes_es3.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_add_quotes_es3.js @@ -1,4 +1,5 @@ -var es3 = /*#__PURE__*/ React.createElement(F, { +import { jsx as _jsx } from "react/jsx-runtime"; +var es3 = /*#__PURE__*/ _jsx(F, { aaa: true, "new": true, "const": true, diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_constructor_as_prop.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_constructor_as_prop.js index 41655d038d51..03dcc6c88919 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_constructor_as_prop.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_constructor_as_prop.js @@ -1,3 +1,4 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { constructor: "foo" }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_deeper_js_namespacing.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_deeper_js_namespacing.js index 009441d89f58..533818b4d4f2 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_deeper_js_namespacing.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_deeper_js_namespacing.js @@ -1 +1,2 @@ -/*#__PURE__*/ React.createElement(Namespace.DeepNamespace.Component, null); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Namespace.DeepNamespace.Component, {}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_elements_as_attributes.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_elements_as_attributes.js index cc0e0765263f..1d1a442b0632 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_elements_as_attributes.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_elements_as_attributes.js @@ -1,3 +1,4 @@ -/*#__PURE__*/ React.createElement("div", { - attr: /*#__PURE__*/ React.createElement("div", null) +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { + attr: /*#__PURE__*/ _jsx("div", {}) }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_js_namespacing.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_js_namespacing.js index fea2ba3e4db5..f0c5dd8a4f3a 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_js_namespacing.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_js_namespacing.js @@ -1 +1,2 @@ -/*#__PURE__*/ React.createElement(Namespace.Component, null); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Namespace.Component, {}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_nested_fragments.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_nested_fragments.js index 3b3891ad11ce..96b46f02529d 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_nested_fragments.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_nested_fragments.js @@ -1 +1,27 @@ -/*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("span", null, "Hello"), /*#__PURE__*/ React.createElement("span", null, "world")), /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("span", null, "Goodbye"), /*#__PURE__*/ React.createElement("span", null, "world")))); +/*#__PURE__*/ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; +_jsx("div", { + children: /*#__PURE__*/ _jsxs(_Fragment, { + children: [ + /*#__PURE__*/ _jsxs(_Fragment, { + children: [ + /*#__PURE__*/ _jsx("span", { + children: "Hello" + }), + /*#__PURE__*/ _jsx("span", { + children: "world" + }) + ] + }), + /*#__PURE__*/ _jsxs(_Fragment, { + children: [ + /*#__PURE__*/ _jsx("span", { + children: "Goodbye" + }), + /*#__PURE__*/ _jsx("span", { + children: "world" + }) + ] + }) + ] + }) +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_no_pragmafrag_if_frag_unused.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_no_pragmafrag_if_frag_unused.js index b63e7dfa5314..af4e8cd4cd2a 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_no_pragmafrag_if_frag_unused.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_no_pragmafrag_if_frag_unused.js @@ -1 +1,4 @@ -/** @jsx dom */ /*#__PURE__*/ dom("div", null, "no fragment is used"); +/** @jsx dom */ /*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { + children: "no fragment is used" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_pragmafrag_and_frag.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_pragmafrag_and_frag.js index 3efc0a3ae3b4..845dae054fe6 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_pragmafrag_and_frag.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_allow_pragmafrag_and_frag.js @@ -1 +1,2 @@ -/** @jsx dom */ /** @jsxFrag DomFrag */ /*#__PURE__*/ dom(DomFrag, null); +/** @jsx dom */ /** @jsxFrag DomFrag */ /*#__PURE__*/ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; +_jsx(_Fragment, {}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_avoid_wrapping_in_extra_parens_if_not_needed.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_avoid_wrapping_in_extra_parens_if_not_needed.js index b48087073c76..c9d1f1bebca2 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_avoid_wrapping_in_extra_parens_if_not_needed.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_avoid_wrapping_in_extra_parens_if_not_needed.js @@ -1,4 +1,13 @@ -var x = /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(Component, null)); -var x = /*#__PURE__*/ React.createElement("div", null, props.children); -var x = /*#__PURE__*/ React.createElement(Composite, null, props.children); -var x = /*#__PURE__*/ React.createElement(Composite, null, /*#__PURE__*/ React.createElement(Composite2, null)); +import { jsx as _jsx } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsx("div", { + children: /*#__PURE__*/ _jsx(Component, {}) +}); +var x = /*#__PURE__*/ _jsx("div", { + children: props.children +}); +var x = /*#__PURE__*/ _jsx(Composite, { + children: props.children +}); +var x = /*#__PURE__*/ _jsx(Composite, { + children: /*#__PURE__*/ _jsx(Composite2, {}) +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_tags.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_tags.js index 6cf5e0a64d36..7c9303d94619 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_tags.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_tags.js @@ -1 +1,2 @@ -var x = /*#__PURE__*/ React.createElement("div", null); +import { jsx as _jsx } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsx("div", {}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_text.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_text.js index 358eed7884aa..8e0accd91751 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_text.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_convert_simple_text.js @@ -1 +1,4 @@ -var x = /*#__PURE__*/ React.createElement("div", null, "text"); +import { jsx as _jsx } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsx("div", { + children: "text" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_unicode_chars_in_attribute.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_unicode_chars_in_attribute.js index 7278c3e7ac3a..05fb5249266b 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_unicode_chars_in_attribute.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_unicode_chars_in_attribute.js @@ -1,3 +1,4 @@ -/*#__PURE__*/ React.createElement(Bla, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Bla, { title: "Ú" }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxattribute.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxattribute.js index c1e7b597e3f2..bc61b3b04bb2 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxattribute.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxattribute.js @@ -1,9 +1,10 @@ -/*#__PURE__*/ React.createElement("div", { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { id: "wôw" }); -/*#__PURE__*/ React.createElement("div", { +/*#__PURE__*/ _jsx("div", { id: "\\w" }); -/*#__PURE__*/ React.createElement("div", { +/*#__PURE__*/ _jsx("div", { id: "w < w" }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_1.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_1.js index 1139c7c0d054..bb1e0ec9ed9d 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_1.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_1.js @@ -1,7 +1,25 @@ -/*#__PURE__*/ React.createElement("div", null, "wow"); -/*#__PURE__*/ React.createElement("div", null, "wôw"); -/*#__PURE__*/ React.createElement("div", null, "w & w"); -/*#__PURE__*/ React.createElement("div", null, "w & w"); -/*#__PURE__*/ React.createElement("div", null, "w   w"); -/*#__PURE__*/ React.createElement("div", null, "this should parse as unicode: ", '\u00a0 '); -/*#__PURE__*/ React.createElement("div", null, "w < w"); +/*#__PURE__*/ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +_jsx("div", { + children: "wow" +}); +/*#__PURE__*/ _jsx("div", { + children: "wôw" +}); +/*#__PURE__*/ _jsx("div", { + children: "w & w" +}); +/*#__PURE__*/ _jsx("div", { + children: "w & w" +}); +/*#__PURE__*/ _jsx("div", { + children: "w   w" +}); +/*#__PURE__*/ _jsxs("div", { + children: [ + "this should parse as unicode: ", + '\u00a0 ' + ] +}); +/*#__PURE__*/ _jsx("div", { + children: "w < w" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_2.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_2.js index 19ec5c31866d..9c55816593ad 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_2.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_escape_xhtml_jsxtext_2.js @@ -1 +1,4 @@ -/*#__PURE__*/ React.createElement("div", null, "this should not parse as unicode: \\u00a0"); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { + children: "this should not parse as unicode: \\u00a0" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_attributed_elements.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_attributed_elements.js index 5f3e6a33218a..6bd26e39a68a 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_attributed_elements.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_attributed_elements.js @@ -1,9 +1,17 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; var HelloMessage = React.createClass({ render: function() { - return /*#__PURE__*/ React.createElement("div", null, "Hello ", this.props.name); + return /*#__PURE__*/ _jsxs("div", { + children: [ + "Hello ", + this.props.name + ] + }); }, displayName: "HelloMessage" }); -React.render(/*#__PURE__*/ React.createElement(HelloMessage, { - name: /*#__PURE__*/ React.createElement("span", null, "Sebastian") +React.render(/*#__PURE__*/ _jsx(HelloMessage, { + name: /*#__PURE__*/ _jsx("span", { + children: "Sebastian" + }) }), mountNode); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_has_own_property_correctly.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_has_own_property_correctly.js index 98e386ff8bbb..ffc1134e2739 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_has_own_property_correctly.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_handle_has_own_property_correctly.js @@ -1 +1,4 @@ -/*#__PURE__*/ React.createElement("hasOwnProperty", null, "testing"); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("hasOwnProperty", { + children: "testing" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_have_correct_comma_in_nested_children.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_have_correct_comma_in_nested_children.js index beb50bc4a03b..8b7ce4097d52 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_have_correct_comma_in_nested_children.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_have_correct_comma_in_nested_children.js @@ -1 +1,16 @@ -var x = /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("br", null)), /*#__PURE__*/ React.createElement(Component, null, foo, /*#__PURE__*/ React.createElement("br", null), bar), /*#__PURE__*/ React.createElement("br", null)); +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsxs("div", { + children: [ + /*#__PURE__*/ _jsx("div", { + children: /*#__PURE__*/ _jsx("br", {}) + }), + /*#__PURE__*/ _jsxs(Component, { + children: [ + foo, + /*#__PURE__*/ _jsx("br", {}), + bar + ] + }), + /*#__PURE__*/ _jsx("br", {}) + ] +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_insert_commas_after_expressions_before_whitespace.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_insert_commas_after_expressions_before_whitespace.js index aae1aaa06227..f2c43d3bf2b5 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_insert_commas_after_expressions_before_whitespace.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_insert_commas_after_expressions_before_whitespace.js @@ -1,4 +1,5 @@ -var x = /*#__PURE__*/ React.createElement("div", { +import { jsx as _jsx } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsx("div", { attr1: "foo" + "bar", attr2: "foo" + "bar" + "baz" + "bug", attr3: "foo" + "bar" + "baz" + "bug", diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_add_quotes_to_identifier_names.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_add_quotes_to_identifier_names.js index b6372d764ed3..e4c24287d66e 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_add_quotes_to_identifier_names.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_add_quotes_to_identifier_names.js @@ -1,4 +1,5 @@ -var e = /*#__PURE__*/ React.createElement(F, { +import { jsx as _jsx } from "react/jsx-runtime"; +var e = /*#__PURE__*/ _jsx(F, { aaa: true, new: true, const: true, diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_mangle_expressioncontainer_attribute_values.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_mangle_expressioncontainer_attribute_values.js index 7f20efef3b25..60f3b788cc0f 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_mangle_expressioncontainer_attribute_values.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_mangle_expressioncontainer_attribute_values.js @@ -1,3 +1,5 @@ -/*#__PURE__*/ React.createElement("button", { - "data-value": "a value\n with\nnewlines\n and spaces" -}, "Button"); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("button", { + "data-value": "a value\n with\nnewlines\n and spaces", + children: "Button" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_nbsp_even_coupled_with_other_whitespace.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_nbsp_even_coupled_with_other_whitespace.js index 4d9f78ad163b..f201230c6d73 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_nbsp_even_coupled_with_other_whitespace.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_nbsp_even_coupled_with_other_whitespace.js @@ -1 +1,4 @@ -/*#__PURE__*/ React.createElement("div", null, "  "); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { + children: "  " +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_tags_with_a_single_child_of_nbsp.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_tags_with_a_single_child_of_nbsp.js index b0d4f70ba9b5..0c47f4fa257d 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_tags_with_a_single_child_of_nbsp.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_not_strip_tags_with_a_single_child_of_nbsp.js @@ -1 +1,4 @@ -/*#__PURE__*/ React.createElement("div", null, " "); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("div", { + children: " " +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_properly_handle_comments_between_props.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_properly_handle_comments_between_props.js index 7984167df4ed..132c7fc7540b 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_properly_handle_comments_between_props.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_properly_handle_comments_between_props.js @@ -1,7 +1,9 @@ -var x = /*#__PURE__*/ React.createElement("div", { +import { jsx as _jsx } from "react/jsx-runtime"; +var x = /*#__PURE__*/ _jsx("div", { /* a multi-line - comment */ attr1: "foo" -}, /*#__PURE__*/ React.createElement("span" // a double-slash comment -, { - attr2: "bar" -})); + comment */ attr1: "foo", + children: /*#__PURE__*/ _jsx("span" // a double-slash comment + , { + attr2: "bar" + }) +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_quote_jsx_attributes.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_quote_jsx_attributes.js index ad72aa574d4e..1d56a5571c92 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_quote_jsx_attributes.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_quote_jsx_attributes.js @@ -1,3 +1,5 @@ -/*#__PURE__*/ React.createElement("button", { - "data-value": "a value" -}, "Button"); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("button", { + "data-value": "a value", + children: "Button" +}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_transform_known_hyphenated_tags.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_transform_known_hyphenated_tags.js index fee3c05e4892..2e1ef2404701 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_transform_known_hyphenated_tags.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_should_transform_known_hyphenated_tags.js @@ -1 +1,2 @@ -/*#__PURE__*/ React.createElement("font-face", null); +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx("font-face", {}); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_first_spread_attributes.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_first_spread_attributes.js index 4b9b77ed536d..7e78e9bc8fe0 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_first_spread_attributes.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_first_spread_attributes.js @@ -1,4 +1,5 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { ...x, y: 2, z: true diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_last_spread_attributes.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_last_spread_attributes.js index 34492fff433d..c17a2a4e6bea 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_last_spread_attributes.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_last_spread_attributes.js @@ -1,4 +1,5 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { y: 2, z: true, ...x diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_middle_spread_attributes.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_middle_spread_attributes.js index 20eed0dc8203..41f4963ad392 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_middle_spread_attributes.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/react_wraps_props_in_react_spread_for_middle_spread_attributes.js @@ -1,4 +1,5 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { y: 2, ...x, z: true diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_builtins_assignment.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_builtins_assignment.js index d3585711e0f1..77317bd836f8 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_builtins_assignment.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_builtins_assignment.js @@ -1,4 +1,5 @@ -var div = /*#__PURE__*/ React.createElement(Component, { +import { jsx as _jsx } from "react/jsx-runtime"; +var div = /*#__PURE__*/ _jsx(Component, { ...props, foo: "bar" }); diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_spread_assignment.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_spread_assignment.js index 20eed0dc8203..41f4963ad392 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_spread_assignment.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/jsx/tests.rs/use_spread_assignment.js @@ -1,4 +1,5 @@ -/*#__PURE__*/ React.createElement(Component, { +/*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; +_jsx(Component, { y: 2, ...x, z: true diff --git a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/refresh/tests.rs/include_hook_signature_in_commonjs.js b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/refresh/tests.rs/include_hook_signature_in_commonjs.js index 86d2eb956f99..7e2348b1182b 100644 --- a/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/refresh/tests.rs/include_hook_signature_in_commonjs.js +++ b/crates/swc_ecma_transforms_react/tests/__swc_snapshots__/src/refresh/tests.rs/include_hook_signature_in_commonjs.js @@ -1,3 +1,4 @@ +import { jsx as _jsx } from "react/jsx-runtime"; var _s = $RefreshSig$(); import { useFancyState } from './hooks'; import useFoo from './foo'; @@ -5,7 +6,9 @@ export default function App() { _s(); const bar = useFancyState(); const foo = useFoo(); - return /*#__PURE__*/ React.createElement("h1", null, bar); + return /*#__PURE__*/ _jsx("h1", { + children: bar + }); } _s(App, "useFancyState{bar}\nuseFoo{foo}", false, function() { return [ diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/autoImport/import-source-pragma/output.mjs b/crates/swc_ecma_transforms_react/tests/jsx/fixture/autoImport/import-source-pragma/output.mjs index 1e68ce1a0fbf..09db6a95012a 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/autoImport/import-source-pragma/output.mjs +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/autoImport/import-source-pragma/output.mjs @@ -1,4 +1,4 @@ -/** @jsxImportSource baz */ import { jsx as _jsx } from "baz/jsx-runtime"; +/** @jsxImportSource baz */ import { jsx as _jsx } from "react/jsx-runtime"; var x = /*#__PURE__*/ _jsx("div", { children: /*#__PURE__*/ _jsx("span", {}) }); diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-1933/output.js b/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-1933/output.js index d6c2da23d6c7..71d068da0c98 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-1933/output.js +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-1933/output.js @@ -1,4 +1 @@ -/* @jsxImportSource react */ import { jsx as _jsx } from "react/jsx-runtime"; -const p = ()=>/*#__PURE__*/ _jsx("div", { - children: "Hello World" - }); +/* @jsxImportSource react */ const p = ()=>/*#__PURE__*/ React.createElement("div", null, "Hello World"); diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-4703/1/output.stderr b/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-4703/1/output.stderr index 5334bddb6303..e69de29bb2d1 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-4703/1/output.stderr +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-4703/1/output.stderr @@ -1,5 +0,0 @@ - x pragma cannot be set when runtime is automatic - ,-[input.js:1:1] - 1 | /** @jsx foo */ - : ^^^^^^^^^^^^^^^ - `---- diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-5099/2/output.stderr b/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-5099/2/output.stderr index 34807b24d37a..e69de29bb2d1 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-5099/2/output.stderr +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/issue-5099/2/output.stderr @@ -1,5 +0,0 @@ - x Runtime must be either `classic` or `automatic`. - ,-[input.js:1:1] - 1 | /** @jsxRuntime typo */ - : ^^^^^^^^^^^^^^^^^^^^^^^ - `---- diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/false-pragma-comment-automatic-runtime/output.stderr b/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/false-pragma-comment-automatic-runtime/output.stderr index 3e34203ed76b..e69de29bb2d1 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/false-pragma-comment-automatic-runtime/output.stderr +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/false-pragma-comment-automatic-runtime/output.stderr @@ -1,5 +0,0 @@ - x pragma cannot be set when runtime is automatic - ,-[input.js:1:1] - 1 | /* @jsx h */ - : ^^^^^^^^^^^^ - `---- diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/true-pragma-comment-automatic-runtime/output.stderr b/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/true-pragma-comment-automatic-runtime/output.stderr index 3e34203ed76b..e69de29bb2d1 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/true-pragma-comment-automatic-runtime/output.stderr +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/true-pragma-comment-automatic-runtime/output.stderr @@ -1,5 +0,0 @@ - x pragma cannot be set when runtime is automatic - ,-[input.js:1:1] - 1 | /* @jsx h */ - : ^^^^^^^^^^^^ - `---- diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/unset-pragma-comment-automatic-runtime/output.stderr b/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/unset-pragma-comment-automatic-runtime/output.stderr index 3e34203ed76b..e69de29bb2d1 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/unset-pragma-comment-automatic-runtime/output.stderr +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/pure/unset-pragma-comment-automatic-runtime/output.stderr @@ -1,5 +0,0 @@ - x pragma cannot be set when runtime is automatic - ,-[input.js:1:1] - 1 | /* @jsx h */ - : ^^^^^^^^^^^^ - `---- diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/react-automatic/pragma-works-with-no-space-at-the-end/output.mjs b/crates/swc_ecma_transforms_react/tests/jsx/fixture/react-automatic/pragma-works-with-no-space-at-the-end/output.mjs index 72c2faa69fc1..b5f1d643b9a4 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/react-automatic/pragma-works-with-no-space-at-the-end/output.mjs +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/react-automatic/pragma-works-with-no-space-at-the-end/output.mjs @@ -1,4 +1,4 @@ -/* @jsxImportSource foo*/ /*#__PURE__*/ import { jsx as _jsx } from "foo/jsx-runtime"; +/* @jsxImportSource foo*/ /*#__PURE__*/ import { jsx as _jsx } from "react/jsx-runtime"; _jsx("div", { children: "Hi" }); diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-allow-multiple-pragmas-per-line/output.js b/crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-allow-multiple-pragmas-per-line/output.js index 510a224d7b86..debd77321a01 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-allow-multiple-pragmas-per-line/output.js +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-allow-multiple-pragmas-per-line/output.js @@ -1,4 +1,4 @@ -/* @jsxRuntime automatic @jsxImportSource preact */ import { jsx as _jsx } from "preact/jsx-runtime"; +/* @jsxRuntime automatic @jsxImportSource preact */ import { jsx as _jsx } from "react/jsx-runtime"; var div = /*#__PURE__*/ _jsx("div", { children: "test" }); diff --git a/crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/pragma-runtime-classsic/output.js b/crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/pragma-runtime-classsic/output.js index 8785f4a11be5..610059e82000 100644 --- a/crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/pragma-runtime-classsic/output.js +++ b/crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/pragma-runtime-classsic/output.js @@ -1,2 +1 @@ -/** @jsxRuntime classic */ -var x = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null)); +/** @jsxRuntime classic */ var x = /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement("span", null)); diff --git a/crates/swc_ecma_transforms_testing/src/lib.rs b/crates/swc_ecma_transforms_testing/src/lib.rs index 407bac688e1f..02646c01534e 100644 --- a/crates/swc_ecma_transforms_testing/src/lib.rs +++ b/crates/swc_ecma_transforms_testing/src/lib.rs @@ -160,14 +160,18 @@ impl Tester<'_> { Ok(stmts.pop().unwrap()) } - pub fn apply_transform( + pub fn apply_transform( &mut self, - tr: T, + tr: F, name: &str, syntax: Syntax, is_module: Option, src: &str, - ) -> Result { + ) -> Result + where + T: Pass, + F: FnOnce(&mut Self) -> T, + { let program = self.with_parser( name, @@ -180,6 +184,7 @@ impl Tester<'_> { }, )?; + let tr = tr(self); Ok(program.apply(tr)) } @@ -248,7 +253,7 @@ pub fn test_transform( { Tester::run(|tester| { let expected = tester.apply_transform( - swc_ecma_utils::DropSpan, + |_| swc_ecma_utils::DropSpan, "output.js", syntax, is_module, @@ -259,8 +264,13 @@ pub fn test_transform( println!("----- Actual -----"); - let tr = (tr(tester), visit_mut_pass(RegeneratorHandler)); - let actual = tester.apply_transform(tr, "input.js", syntax, is_module, input)?; + let actual = tester.apply_transform( + |t| (tr(t), visit_mut_pass(RegeneratorHandler)), + "input.js", + syntax, + is_module, + input, + )?; match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { @@ -336,7 +346,7 @@ pub fn test_inline_input_output( let expected_src = Tester::run(|tester| { let expected_program = - tester.apply_transform(noop_pass(), "expected.js", syntax, is_module, expected)?; + tester.apply_transform(|_| noop_pass(), "expected.js", syntax, is_module, expected)?; let expected_src = tester.print(&expected_program, &Default::default()); @@ -352,8 +362,6 @@ pub fn test_inline_input_output( let actual_src = Tester::run_captured(|tester| { println!("----- {} -----\n{}", Color::Green.paint("Input"), input); - let tr = tr(tester); - println!("----- {} -----", Color::Green.paint("Actual")); let actual = tester.apply_transform(tr, "input.js", syntax, is_module, input)?; @@ -417,7 +425,7 @@ pub fn test_inlined_transform( test_fixture_inner( syntax, - Box::new(move |tester| Box::new(tr(tester))), + tr, input, &snapshot_dir.join(format!("{test_name}.js")), FixtureTestConfig { @@ -536,9 +544,13 @@ where P: Pass, { Tester::run(|tester| { - let tr = (tr(tester), visit_mut_pass(RegeneratorHandler)); - - let program = tester.apply_transform(tr, "input.js", syntax, Some(true), input)?; + let program = tester.apply_transform( + |t| (tr(t), visit_mut_pass(RegeneratorHandler)), + "input.js", + syntax, + Some(true), + input, + )?; match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { @@ -581,10 +593,8 @@ where P: Pass, { Tester::run(|tester| { - let tr = (tr(tester), visit_mut_pass(RegeneratorHandler)); - let program = tester.apply_transform( - tr, + |t| (tr(t), visit_mut_pass(RegeneratorHandler)), "input.js", syntax, Some(true), @@ -859,22 +869,19 @@ pub fn test_fixture

( { let input = fs::read_to_string(input).unwrap(); - test_fixture_inner( - syntax, - Box::new(|tester| Box::new(tr(tester))), - &input, - output, - config, - ); + test_fixture_inner(syntax, tr, &input, output, config); } -fn test_fixture_inner<'a>( +fn test_fixture_inner( syntax: Syntax, - tr: Box Box>, + tr: F, input: &str, output: &Path, config: FixtureTestConfig, -) { +) where + P: Pass, + F: FnOnce(&mut Tester) -> P, +{ let _logger = testing::init(); let expected = read_to_string(output); @@ -882,8 +889,13 @@ fn test_fixture_inner<'a>( let expected = expected.unwrap_or_default(); let expected_src = Tester::run(|tester| { - let expected_program = - tester.apply_transform(noop_pass(), "expected.js", syntax, config.module, &expected)?; + let expected_program = tester.apply_transform( + |_| noop_pass(), + "expected.js", + syntax, + config.module, + &expected, + )?; let expected_src = tester.print(&expected_program, &tester.comments.clone()); @@ -907,8 +919,6 @@ fn test_fixture_inner<'a>( let (actual_src, stderr) = Tester::run_captured(|tester| { eprintln!("----- {} -----\n{}", Color::Green.paint("Input"), input); - let tr = tr(tester); - eprintln!("----- {} -----", Color::Green.paint("Actual")); let actual = tester.apply_transform(tr, "input.js", syntax, config.module, input)?; diff --git a/crates/swc_ecma_transforms_typescript/Cargo.toml b/crates/swc_ecma_transforms_typescript/Cargo.toml index 13e6c4459978..133bafc52bbd 100644 --- a/crates/swc_ecma_transforms_typescript/Cargo.toml +++ b/crates/swc_ecma_transforms_typescript/Cargo.toml @@ -38,6 +38,7 @@ swc_ecma_codegen = { version = "15.0.1", path = "../swc_ecma_codegen swc_ecma_parser = { version = "17.2.1", path = "../swc_ecma_parser" } swc_ecma_transforms_compat = { version = "20.0.0", path = "../swc_ecma_transforms_compat" } swc_ecma_transforms_proposal = { version = "18.0.0", path = "../swc_ecma_transforms_proposal" } +swc_ecma_transforms_react = { version = "20.0.0", path = "../swc_ecma_transforms_react" } swc_ecma_transforms_testing = { version = "21.0.0", path = "../swc_ecma_transforms_testing" } testing = { version = "14.0.0", path = "../testing" } diff --git a/crates/swc_ecma_transforms_typescript/src/config.rs b/crates/swc_ecma_transforms_typescript/src/config.rs index 956d2e28a340..797256077548 100644 --- a/crates/swc_ecma_transforms_typescript/src/config.rs +++ b/crates/swc_ecma_transforms_typescript/src/config.rs @@ -1,4 +1,3 @@ -use bytes_str::BytesStr; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Serialize, Deserialize, Clone, Copy)] @@ -36,17 +35,6 @@ pub struct Config { pub ts_enum_is_mutable: bool, } -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct TsxConfig { - /// Note: this pass handle jsx directives in comments - #[serde(default)] - pub pragma: Option, - - /// Note: this pass handle jsx directives in comments - #[serde(default)] - pub pragma_frag: Option, -} - #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum TsImportExportAssignConfig { /// - Rewrite `import foo = require("foo")` to `var foo = require("foo")` diff --git a/crates/swc_ecma_transforms_typescript/src/typescript.rs b/crates/swc_ecma_transforms_typescript/src/typescript.rs index 685f8c36acf3..392d07c76fc2 100644 --- a/crates/swc_ecma_transforms_typescript/src/typescript.rs +++ b/crates/swc_ecma_transforms_typescript/src/typescript.rs @@ -1,21 +1,13 @@ use std::mem; use rustc_hash::FxHashSet; -use swc_atoms::atom; -use swc_common::{comments::Comments, sync::Lrc, util::take::Take, Mark, SourceMap, Span, Spanned}; +use swc_common::{util::take::Take, Mark, Span, Spanned}; use swc_ecma_ast::*; -use swc_ecma_transforms_react::{parse_expr_for_jsx, JsxDirectives}; use swc_ecma_visit::{visit_mut_pass, VisitMut, VisitMutWith}; pub use crate::config::*; use crate::{strip_import_export::StripImportExport, strip_type::StripType, transform::transform}; -macro_rules! static_str { - ($s:expr) => { - $s.into() - }; -} - pub fn typescript(config: Config, unresolved_mark: Mark, top_level_mark: Mark) -> impl Pass { debug_assert_ne!(unresolved_mark, top_level_mark); @@ -140,133 +132,3 @@ impl EsModuleDecl for ModuleItem { .is_some_and(ModuleDecl::is_es_module_decl) } } - -pub fn tsx( - cm: Lrc, - config: Config, - tsx_config: TsxConfig, - comments: C, - unresolved_mark: Mark, - top_level_mark: Mark, -) -> impl Pass -where - C: Comments, -{ - visit_mut_pass(TypeScriptReact { - config, - tsx_config, - id_usage: Default::default(), - comments, - cm, - top_level_mark, - unresolved_mark, - }) -} - -/// Get an [Id] which will used by expression. -/// -/// For `React#1.createElement`, this returns `React#1`. -fn id_for_jsx(e: &Expr) -> Option { - match e { - Expr::Ident(i) => Some(i.to_id()), - Expr::Member(MemberExpr { obj, .. }) => Some(id_for_jsx(obj)).flatten(), - Expr::Lit(Lit::Null(..)) => Some((atom!("null"), Default::default())), - _ => None, - } -} - -struct TypeScriptReact -where - C: Comments, -{ - config: Config, - tsx_config: TsxConfig, - id_usage: FxHashSet, - comments: C, - cm: Lrc, - top_level_mark: Mark, - unresolved_mark: Mark, -} - -impl VisitMut for TypeScriptReact -where - C: Comments, -{ - fn visit_mut_module(&mut self, n: &mut Module) { - // We count `React` or pragma from config as ident usage and do not strip it - // from import statement. - // But in `verbatim_module_syntax` mode, we do not remove any unused imports. - // So we do not need to collect usage info. - if !self.config.verbatim_module_syntax { - let pragma = parse_expr_for_jsx( - &self.cm, - "pragma", - self.tsx_config - .pragma - .clone() - .unwrap_or_else(|| static_str!("React.createElement")), - self.top_level_mark, - ); - - let pragma_frag = parse_expr_for_jsx( - &self.cm, - "pragma", - self.tsx_config - .pragma_frag - .clone() - .unwrap_or_else(|| static_str!("React.Fragment")), - self.top_level_mark, - ); - - let pragma_id = id_for_jsx(&pragma).unwrap(); - let pragma_frag_id = id_for_jsx(&pragma_frag).unwrap(); - - self.id_usage.insert(pragma_id); - self.id_usage.insert(pragma_frag_id); - } - - if !self.config.verbatim_module_syntax { - let span = if n.shebang.is_some() { - n.span - .with_lo(n.body.first().map(|s| s.span_lo()).unwrap_or(n.span.lo)) - } else { - n.span - }; - - let JsxDirectives { - pragma, - pragma_frag, - .. - } = self.comments.with_leading(span.lo, |comments| { - JsxDirectives::from_comments(&self.cm, span, comments, self.top_level_mark) - }); - - if let Some(pragma) = pragma { - if let Some(pragma_id) = id_for_jsx(&pragma) { - self.id_usage.insert(pragma_id); - } - } - - if let Some(pragma_frag) = pragma_frag { - if let Some(pragma_frag_id) = id_for_jsx(&pragma_frag) { - self.id_usage.insert(pragma_frag_id); - } - } - } - } - - fn visit_mut_script(&mut self, _: &mut Script) { - // skip script - } - - fn visit_mut_program(&mut self, n: &mut Program) { - n.visit_mut_children_with(self); - - n.visit_mut_with(&mut TypeScript { - config: mem::take(&mut self.config), - unresolved_mark: self.unresolved_mark, - top_level_mark: self.top_level_mark, - id_usage: mem::take(&mut self.id_usage), - }); - } -} diff --git a/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_jsx_prag.js b/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_jsx_prag.js index 1374ba9de71b..f2c88ae894a3 100644 --- a/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_jsx_prag.js +++ b/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_jsx_prag.js @@ -1,4 +1,4 @@ -/** @jsx h */ import html, { h } from "example"; +/** @jsxRuntime classic */ /** @jsx h */ import html, { h } from "example"; serve((_req)=>html({ - body: /*#__PURE__*/ h("div", null, "Hello World!") -})); + body: /*#__PURE__*/ h("div", null, "Hello World!") + })); diff --git a/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_shebang_jsx_prag.js b/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_shebang_jsx_prag.js index 2c38af8d6e2e..ce3ff94318ea 100644 --- a/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_shebang_jsx_prag.js +++ b/crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/imports_not_used_as_values_shebang_jsx_prag.js @@ -1,5 +1,5 @@ #!/usr/bin/env -S deno run -A -/** @jsx h */ import html, { h } from "example"; +/** @jsxRuntime classic */ /** @jsx h */ import html, { h } from "example"; serve((_req)=>html({ - body: /*#__PURE__*/ h("div", null, "Hello World!") -})); + body: /*#__PURE__*/ h("div", null, "Hello World!") + })); diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/input.tsx b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/input.tsx index e3027e12e5f1..af112ff8bb23 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/input.tsx +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/input.tsx @@ -1,3 +1,5 @@ +/* @jsxRuntime classic */ +// import React from "react"; import ReactDOM from "react-dom"; import { _Component } from "./Component"; diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/output.js b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/output.js index 6743365e4828..61f5281b8179 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/output.js +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-6923/output.js @@ -1,4 +1,6 @@ +/* @jsxRuntime classic */ // +import React from "react"; import ReactDOM from "react-dom"; import { _Component } from "./Component"; -const App = React.createElement("div", null, React.createElement(_Component, null), React.createElement("p", null, "Hello World")); +const App = /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(_Component, null), /*#__PURE__*/ React.createElement("p", null, "Hello World")); ReactDOM.render(App, window.document.getElementById("react_root")); diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/input.tsx b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/input.tsx index 27ad390aca3b..88393732815b 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/input.tsx +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/input.tsx @@ -1,3 +1,4 @@ +/* @jsxRuntime classic */ /* @jsx h */ /* @jsxFrag null */ -<>; \ No newline at end of file +<>; diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/output.js b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/output.js index d2b2afe8389d..495991ee895a 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/output.js +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/issue-7539/output.js @@ -1 +1 @@ -/* @jsx h */ /* @jsxFrag null */ React.createElement(React.Fragment, null); +/* @jsxRuntime classic */ /* @jsx h */ /* @jsxFrag null */ /*#__PURE__*/ h(null, null); diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/1/output.js b/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/1/output.js index 84341e8e32a4..bc1be4d39025 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/1/output.js +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/1/output.js @@ -1,8 +1,15 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { dirname } from "node:path"; export default function IndexPage(props) { - return React.createElement("div", null, "abc: ", props.abc, React.createElement("svg", { - viewBox: "0 -85 600 600" - })); + return /*#__PURE__*/ _jsxs("div", { + children: [ + "abc: ", + props.abc, + /*#__PURE__*/ _jsx("svg", { + viewBox: "0 -85 600 600" + }) + ] + }); } export function getServerSideProps() { return { diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/2/output.js b/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/2/output.js index 99c5a367821c..c8438582a96a 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/2/output.js +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/2/output.js @@ -1,12 +1,20 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { dirname } from "node:path"; export default function IndexPage(props) { - return React.createElement("div", null, "abc: ", props.abc, React.createElement("svg", { - viewBox: "0 -85 600 600" - }, React.createElement("path", { - fillRule: "evenodd", - d: "M513 256.5C513 398.161 398.161 513 256.5 513C114.839 513 0 398.161 0 256.5C0 114.839 114.839 0 256.5 0C398.161 0 513 114.839 513 256.5ZM211.146 305.243L369.885 145L412 185.878L253.26 346.122L211.146 387L101 275.811L143.115 234.932L211.146 305.243Z", - fill: "#fff" - }))); + return /*#__PURE__*/ _jsxs("div", { + children: [ + "abc: ", + props.abc, + /*#__PURE__*/ _jsx("svg", { + viewBox: "0 -85 600 600", + children: /*#__PURE__*/ _jsx("path", { + fillRule: "evenodd", + d: "M513 256.5C513 398.161 398.161 513 256.5 513C114.839 513 0 398.161 0 256.5C0 114.839 114.839 0 256.5 0C398.161 0 513 114.839 513 256.5ZM211.146 305.243L369.885 145L412 185.878L253.26 346.122L211.146 387L101 275.811L143.115 234.932L211.146 305.243Z", + fill: "#fff" + }) + }) + ] + }); } export function getServerSideProps() { return { diff --git a/crates/swc_ecma_transforms_typescript/tests/fixture/next/server/render/1/output.js b/crates/swc_ecma_transforms_typescript/tests/fixture/next/server/render/1/output.js index f613ecac0590..f1319e4c2d58 100644 --- a/crates/swc_ecma_transforms_typescript/tests/fixture/next/server/render/1/output.js +++ b/crates/swc_ecma_transforms_typescript/tests/fixture/next/server/render/1/output.js @@ -1,3 +1,4 @@ +import { jsx as _jsx } from "react/jsx-runtime"; import { Writable } from "stream"; import * as ReactDOMServer from "react-dom/server"; import { StyleRegistry, createStyleRegistry } from "styled-jsx"; @@ -232,15 +233,19 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { locales: renderOpts.locales, defaultLocale: renderOpts.defaultLocale, AppTree: (props)=>{ - return React.createElement(AppContainer, null, React.createElement(App, { - ...props, - Component: Component, - router: router - })); + return /*#__PURE__*/ _jsx(AppContainer, { + children: /*#__PURE__*/ _jsx(App, { + ...props, + Component: Component, + router: router + }) + }); }, defaultGetInitialProps: async (docCtx)=>{ const enhanceApp = (AppComp)=>{ - return (props)=>React.createElement(AppComp, props); + return (props)=>/*#__PURE__*/ _jsx(AppComp, { + ...props + }); }; const { html, head } = await docCtx.renderPage({ enhanceApp @@ -264,26 +269,31 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { let head = defaultHead(inAmpMode); let scriptLoader = {}; const nextExport = !isSSG && (renderOpts.nextExport || dev && (isAutoExport || isFallback)); - const AppContainer = ({ children })=>React.createElement(RouterContext.Provider, { - value: router - }, React.createElement(AmpStateContext.Provider, { - value: ampState - }, React.createElement(HeadManagerContext.Provider, { - value: { - updateHead: (state)=>{ - head = state; - }, - updateScripts: (scripts)=>{ - scriptLoader = scripts; - }, - scripts: {}, - mountedInstances: new Set() - } - }, React.createElement(LoadableContext.Provider, { - value: (moduleName)=>reactLoadableModules.push(moduleName) - }, React.createElement(StyleRegistry, { - registry: jsxStyleRegistry - }, children))))); + const AppContainer = ({ children })=>/*#__PURE__*/ _jsx(RouterContext.Provider, { + value: router, + children: /*#__PURE__*/ _jsx(AmpStateContext.Provider, { + value: ampState, + children: /*#__PURE__*/ _jsx(HeadManagerContext.Provider, { + value: { + updateHead: (state)=>{ + head = state; + }, + updateScripts: (scripts)=>{ + scriptLoader = scripts; + }, + scripts: {}, + mountedInstances: new Set() + }, + children: /*#__PURE__*/ _jsx(LoadableContext.Provider, { + value: (moduleName)=>reactLoadableModules.push(moduleName), + children: /*#__PURE__*/ _jsx(StyleRegistry, { + registry: jsxStyleRegistry, + children: children + }) + }) + }) + }) + }); props = await loadGetInitialProps(App, { AppTree: ctx.AppTree, Component, @@ -532,7 +542,7 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { if (Document.getInitialProps) { const renderPage = (options = {})=>{ if (ctx.err && ErrorDebug) { - const html = ReactDOMServer.renderToString(React.createElement(ErrorDebug, { + const html = ReactDOMServer.renderToString(/*#__PURE__*/ _jsx(ErrorDebug, { error: ctx.err })); return { @@ -544,11 +554,13 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { throw new Error(`'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`); } const { App: EnhancedApp, Component: EnhancedComponent } = enhanceComponents(options, App, Component); - const html = ReactDOMServer.renderToString(React.createElement(AppContainer, null, React.createElement(EnhancedApp, { - Component: EnhancedComponent, - router: router, - ...props - }))); + const html = ReactDOMServer.renderToString(/*#__PURE__*/ _jsx(AppContainer, { + children: /*#__PURE__*/ _jsx(EnhancedApp, { + Component: EnhancedComponent, + router: router, + ...props + }) + })); return { html, head @@ -569,7 +581,7 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { bodyResult: piperFromArray([ docProps.html ]), - documentElement: (htmlProps)=>React.createElement(Document, { + documentElement: (htmlProps)=>/*#__PURE__*/ _jsx(Document, { ...htmlProps, ...docProps }), @@ -578,13 +590,15 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { styles: docProps.styles }; } else { - const content = ctx.err && ErrorDebug ? React.createElement(ErrorDebug, { + const content = ctx.err && ErrorDebug ? /*#__PURE__*/ _jsx(ErrorDebug, { error: ctx.err - }) : React.createElement(AppContainer, null, React.createElement(App, { - ...props, - Component: Component, - router: router - })); + }) : /*#__PURE__*/ _jsx(AppContainer, { + children: /*#__PURE__*/ _jsx(App, { + ...props, + Component: Component, + router: router + }) + }); const bodyResult = concurrentFeatures ? await renderToStream(content, generateStaticHTML) : piperFromArray([ ReactDOMServer.renderToString(content) ]); @@ -661,11 +675,13 @@ export async function renderToHTML(req, res, pathname, query, renderOpts) { styles: documentResult.styles, useMaybeDeferContent }; - const documentHTML = ReactDOMServer.renderToStaticMarkup(React.createElement(AmpStateContext.Provider, { - value: ampState - }, React.createElement(HtmlContext.Provider, { - value: htmlProps - }, documentResult.documentElement(htmlProps)))); + const documentHTML = ReactDOMServer.renderToStaticMarkup(/*#__PURE__*/ _jsx(AmpStateContext.Provider, { + value: ampState, + children: /*#__PURE__*/ _jsx(HtmlContext.Provider, { + value: htmlProps, + children: documentResult.documentElement(htmlProps) + }) + })); if (process.env.NODE_ENV !== "production") { const nonRenderedComponents = []; const expectedDocComponents = [ diff --git a/crates/swc_ecma_transforms_typescript/tests/strip.rs b/crates/swc_ecma_transforms_typescript/tests/strip.rs index 73845810526a..24454125ce2d 100644 --- a/crates/swc_ecma_transforms_typescript/tests/strip.rs +++ b/crates/swc_ecma_transforms_typescript/tests/strip.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use swc_common::{comments::NoopComments, pass::Optional, Mark}; +use swc_common::{pass::Optional, Mark}; use swc_ecma_ast::Pass; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::resolver; @@ -15,7 +15,7 @@ use swc_ecma_transforms_proposal::decorators; use swc_ecma_transforms_react::jsx; use swc_ecma_transforms_testing::{test, test_exec, test_fixture, Tester}; use swc_ecma_transforms_typescript::{ - tsx, typescript, ImportsNotUsedAsValues, TsImportExportAssignConfig, TsxConfig, + typescript, ImportsNotUsedAsValues, TsImportExportAssignConfig, }; fn tr(t: &mut Tester) -> impl Pass { @@ -36,20 +36,22 @@ fn tr_config( ..Default::default() }); + let (before_resolver, after_resolver) = jsx( + t.cm.clone(), + Some(t.comments.clone()), + Default::default(), + unresolved_mark, + ); + ( Optional::new( decorators(decorators_config.unwrap_or_default()), has_decorators, ), + before_resolver, resolver(unresolved_mark, top_level_mark, true), typescript(config, unresolved_mark, top_level_mark), - jsx( - t.cm.clone(), - None::, - Default::default(), - top_level_mark, - unresolved_mark, - ), + after_resolver, Optional::new(class_fields_use_set(true), !use_define_for_class_fields), ) } @@ -58,27 +60,24 @@ fn tsxr(t: &Tester) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); + let (before_resolver_jsx, after_resolver_jsx) = swc_ecma_transforms_react::jsx( + t.cm.clone(), + Some(t.comments.clone()), + swc_ecma_transforms_react::Options::default(), + unresolved_mark, + ); + + let config = typescript::Config { + no_empty_export: true, + import_not_used_as_values: ImportsNotUsedAsValues::Remove, + ..Default::default() + }; + ( + before_resolver_jsx, resolver(unresolved_mark, top_level_mark, false), - tsx( - t.cm.clone(), - typescript::Config { - no_empty_export: true, - import_not_used_as_values: ImportsNotUsedAsValues::Remove, - ..Default::default() - }, - TsxConfig::default(), - t.comments.clone(), - unresolved_mark, - top_level_mark, - ), - swc_ecma_transforms_react::jsx( - t.cm.clone(), - Some(t.comments.clone()), - swc_ecma_transforms_react::Options::default(), - top_level_mark, - unresolved_mark, - ), + typescript(config, unresolved_mark, top_level_mark), + after_resolver_jsx, ) } @@ -1806,7 +1805,8 @@ test!( }), |t| tsxr(t), imports_not_used_as_values_jsx_prag, - r#"/** @jsx h */ + r#"/** @jsxRuntime classic */ +/** @jsx h */ import html, { h } from "example"; serve((_req) => html({ @@ -1824,6 +1824,7 @@ test!( |t| tsxr(t), imports_not_used_as_values_shebang_jsx_prag, r#"#!/usr/bin/env -S deno run -A +/** @jsxRuntime classic */ /** @jsx h */ import html, { h } from "example"; serve((_req) => @@ -2811,20 +2812,17 @@ test!( test!( Syntax::Typescript(TsSyntax::default()), - |t| { + |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), - tsx( - t.cm.clone(), + typescript( typescript::Config { verbatim_module_syntax: false, ..Default::default() }, - TsxConfig::default(), - t.comments.clone(), unresolved_mark, top_level_mark, ), diff --git a/crates/swc_node_bundler/src/loaders/swc.rs b/crates/swc_node_bundler/src/loaders/swc.rs index 96991bab148d..d2467d204c88 100644 --- a/crates/swc_node_bundler/src/loaders/swc.rs +++ b/crates/swc_node_bundler/src/loaders/swc.rs @@ -169,6 +169,14 @@ impl SwcLoader { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); + let (mut before_resolver_jsx, mut after_resolver_jsx) = jsx( + self.compiler.cm.clone(), + Some(self.compiler.comments().clone()), + Default::default(), + unresolved_mark, + ); + + program.mutate(&mut before_resolver_jsx); program.mutate(&mut resolver(unresolved_mark, top_level_mark, false)); program.mutate(&mut typescript( Default::default(), @@ -176,13 +184,7 @@ impl SwcLoader { top_level_mark, )); - program.mutate(&mut jsx( - self.compiler.cm.clone(), - None::, - Default::default(), - top_level_mark, - unresolved_mark, - )); + program.mutate(&mut after_resolver_jsx); program.mutate(&mut inline_globals( unresolved_mark, @@ -266,6 +268,14 @@ impl SwcLoader { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); + let (mut before_resolver_jsx, mut after_resolver_jsx) = jsx( + self.compiler.cm.clone(), + None::, + Default::default(), + unresolved_mark, + ); + + program.mutate(&mut before_resolver_jsx); program.mutate(&mut resolver(unresolved_mark, top_level_mark, false)); program.mutate(&mut typescript( Default::default(), @@ -273,13 +283,7 @@ impl SwcLoader { top_level_mark, )); - program.mutate(&mut jsx( - self.compiler.cm.clone(), - None::, - Default::default(), - top_level_mark, - unresolved_mark, - )); + program.mutate(&mut after_resolver_jsx); program.mutate(&mut inline_globals( unresolved_mark, diff --git a/crates/swc_node_bundler/tests/pass/swcrc/jsx/issue-884/output/entry.js b/crates/swc_node_bundler/tests/pass/swcrc/jsx/issue-884/output/entry.js index ac2d9002ebf7..ce7043185107 100644 --- a/crates/swc_node_bundler/tests/pass/swcrc/jsx/issue-884/output/entry.js +++ b/crates/swc_node_bundler/tests/pass/swcrc/jsx/issue-884/output/entry.js @@ -1,2 +1,2847 @@ -var Divider = React.createElement("div", null); +function __swcpack_require__(mod) { + function interop(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for(var key in obj){ + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } + newObj.default = obj; + return newObj; + } + } + var cache; + if (cache) { + return cache; + } + var module = { + exports: {} + }; + mod(module, module.exports); + cache = interop(module.exports); + return cache; +} +var load = __swcpack_require__.bind(void 0, function(module, exports) { + /* +object-assign +(c) Sindre Sorhus +@license MIT +*/ 'use strict'; + /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var propIsEnumerable = Object.prototype.propertyIsEnumerable; + function toObject(val) { + if (val === null || val === undefined) throw new TypeError('Object.assign cannot be called with null or undefined'); + return Object(val); + } + function shouldUseNative() { + try { + if (!Object.assign) return false; + // Detect buggy property enumeration order in older V8 versions. + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') return false; + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for(var i = 0; i < 10; i++)test2['_' + String.fromCharCode(i)] = i; + var order2 = Object.getOwnPropertyNames(test2).map(function(n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') return false; + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function(letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') return false; + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } + } + module.exports = shouldUseNative() ? Object.assign : function(target, source) { + var from; + var to = toObject(target); + var symbols; + for(var s = 1; s < arguments.length; s++){ + from = Object(arguments[s]); + for(var key in from)if (hasOwnProperty.call(from, key)) to[key] = from[key]; + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for(var i = 0; i < symbols.length; i++)if (propIsEnumerable.call(from, symbols[i])) to[symbols[i]] = from[symbols[i]]; + } + } + return to; + }; +}); +var load1 = __swcpack_require__.bind(void 0, function(module, exports) { + /** @license React v17.0.2 + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ 'use strict'; + var l = load(), n = 60103, p = 60106; + exports.Fragment = 60107; + exports.StrictMode = 60108; + exports.Profiler = 60114; + var q = 60109, r = 60110, t = 60112; + exports.Suspense = 60113; + var u = 60115, v = 60116; + if ("function" === typeof Symbol && Symbol.for) { + var w = Symbol.for; + n = w("react.element"); + p = w("react.portal"); + exports.Fragment = w("react.fragment"); + exports.StrictMode = w("react.strict_mode"); + exports.Profiler = w("react.profiler"); + q = w("react.provider"); + r = w("react.context"); + t = w("react.forward_ref"); + exports.Suspense = w("react.suspense"); + u = w("react.memo"); + v = w("react.lazy"); + } + var x = "function" === typeof Symbol && Symbol.iterator; + function y(a) { + if (null === a || "object" !== typeof a) return null; + a = x && a[x] || a["@@iterator"]; + return "function" === typeof a ? a : null; + } + function z(a) { + for(var b = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, c = 1; c < arguments.length; c++)b += "&args[]=" + encodeURIComponent(arguments[c]); + return "Minified React error #" + a + "; visit " + b + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; + } + var A = { + isMounted: function() { + return !1; + }, + enqueueForceUpdate: function() {}, + enqueueReplaceState: function() {}, + enqueueSetState: function() {} + }, B = {}; + function C(a, b, c) { + this.props = a; + this.context = b; + this.refs = B; + this.updater = c || A; + } + C.prototype.isReactComponent = {}; + C.prototype.setState = function(a, b) { + if ("object" !== typeof a && "function" !== typeof a && null != a) throw Error(z(85)); + this.updater.enqueueSetState(this, a, b, "setState"); + }; + C.prototype.forceUpdate = function(a) { + this.updater.enqueueForceUpdate(this, a, "forceUpdate"); + }; + function D() {} + D.prototype = C.prototype; + function E(a, b, c) { + this.props = a; + this.context = b; + this.refs = B; + this.updater = c || A; + } + var F = E.prototype = new D; + F.constructor = E; + l(F, C.prototype); + F.isPureReactComponent = !0; + var G = { + current: null + }, H = Object.prototype.hasOwnProperty, I = { + key: !0, + ref: !0, + __self: !0, + __source: !0 + }; + function J(a, b, c) { + var e, d = {}, k = null, h = null; + if (null != b) for(e in void 0 !== b.ref && (h = b.ref), void 0 !== b.key && (k = "" + b.key), b)H.call(b, e) && !I.hasOwnProperty(e) && (d[e] = b[e]); + var g = arguments.length - 2; + if (1 === g) d.children = c; + else if (1 < g) { + for(var f = Array(g), m = 0; m < g; m++)f[m] = arguments[m + 2]; + d.children = f; + } + if (a && a.defaultProps) for(e in g = a.defaultProps, g)void 0 === d[e] && (d[e] = g[e]); + return { + $$typeof: n, + type: a, + key: k, + ref: h, + props: d, + _owner: G.current + }; + } + function K(a, b) { + return { + $$typeof: n, + type: a.type, + key: b, + ref: a.ref, + props: a.props, + _owner: a._owner + }; + } + function L(a) { + return "object" === typeof a && null !== a && a.$$typeof === n; + } + function escape(a) { + var b = { + "=": "=0", + ":": "=2" + }; + return "$" + a.replace(/[=:]/g, function(a) { + return b[a]; + }); + } + var M = /\/+/g; + function N(a, b) { + return "object" === typeof a && null !== a && null != a.key ? escape("" + a.key) : b.toString(36); + } + function O(a, b, c, e, d) { + var k = typeof a; + if ("undefined" === k || "boolean" === k) a = null; + var h = !1; + if (null === a) h = !0; + else switch(k){ + case "string": + case "number": + h = !0; + break; + case "object": + switch(a.$$typeof){ + case n: + case p: + h = !0; + } + } + if (h) return h = a, d = d(h), a = "" === e ? "." + N(h, 0) : e, Array.isArray(d) ? (c = "", null != a && (c = a.replace(M, "$&/") + "/"), O(d, b, c, "", function(a) { + return a; + })) : null != d && (L(d) && (d = K(d, c + (!d.key || h && h.key === d.key ? "" : ("" + d.key).replace(M, "$&/") + "/") + a)), b.push(d)), 1; + h = 0; + e = "" === e ? "." : e + ":"; + if (Array.isArray(a)) for(var g = 0; g < a.length; g++){ + k = a[g]; + var f = e + N(k, g); + h += O(k, b, c, f, d); + } + else if (f = y(a), "function" === typeof f) for(a = f.call(a), g = 0; !(k = a.next()).done;)k = k.value, f = e + N(k, g++), h += O(k, b, c, f, d); + else if ("object" === k) throw b = "" + a, Error(z(31, "[object Object]" === b ? "object with keys {" + Object.keys(a).join(", ") + "}" : b)); + return h; + } + function P(a, b, c) { + if (null == a) return a; + var e = [], d = 0; + O(a, e, "", "", function(a) { + return b.call(c, a, d++); + }); + return e; + } + function Q(a) { + if (-1 === a._status) { + var b = a._result; + b = b(); + a._status = 0; + a._result = b; + b.then(function(b) { + 0 === a._status && (b = b.default, a._status = 1, a._result = b); + }, function(b) { + 0 === a._status && (a._status = 2, a._result = b); + }); + } + if (1 === a._status) return a._result; + throw a._result; + } + var R = { + current: null + }; + function S() { + var a = R.current; + if (null === a) throw Error(z(321)); + return a; + } + var T = { + ReactCurrentDispatcher: R, + ReactCurrentBatchConfig: { + transition: 0 + }, + ReactCurrentOwner: G, + IsSomeRendererActing: { + current: !1 + }, + assign: l + }; + exports.Children = { + map: P, + forEach: function(a, b, c) { + P(a, function() { + b.apply(this, arguments); + }, c); + }, + count: function(a) { + var b = 0; + P(a, function() { + b++; + }); + return b; + }, + toArray: function(a) { + return P(a, function(a) { + return a; + }) || []; + }, + only: function(a) { + if (!L(a)) throw Error(z(143)); + return a; + } + }; + exports.Component = C; + exports.PureComponent = E; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = T; + exports.cloneElement = function(a, b, c) { + if (null === a || void 0 === a) throw Error(z(267, a)); + var e = l({}, a.props), d = a.key, k = a.ref, h = a._owner; + if (null != b) { + void 0 !== b.ref && (k = b.ref, h = G.current); + void 0 !== b.key && (d = "" + b.key); + if (a.type && a.type.defaultProps) var g = a.type.defaultProps; + for(f in b)H.call(b, f) && !I.hasOwnProperty(f) && (e[f] = void 0 === b[f] && void 0 !== g ? g[f] : b[f]); + } + var f = arguments.length - 2; + if (1 === f) e.children = c; + else if (1 < f) { + g = Array(f); + for(var m = 0; m < f; m++)g[m] = arguments[m + 2]; + e.children = g; + } + return { + $$typeof: n, + type: a.type, + key: d, + ref: k, + props: e, + _owner: h + }; + }; + exports.createContext = function(a, b) { + void 0 === b && (b = null); + a = { + $$typeof: r, + _calculateChangedBits: b, + _currentValue: a, + _currentValue2: a, + _threadCount: 0, + Provider: null, + Consumer: null + }; + a.Provider = { + $$typeof: q, + _context: a + }; + return a.Consumer = a; + }; + exports.createElement = J; + exports.createFactory = function(a) { + var b = J.bind(null, a); + b.type = a; + return b; + }; + exports.createRef = function() { + return { + current: null + }; + }; + exports.forwardRef = function(a) { + return { + $$typeof: t, + render: a + }; + }; + exports.isValidElement = L; + exports.lazy = function(a) { + return { + $$typeof: v, + _payload: { + _status: -1, + _result: a + }, + _init: Q + }; + }; + exports.memo = function(a, b) { + return { + $$typeof: u, + type: a, + compare: void 0 === b ? null : b + }; + }; + exports.useCallback = function(a, b) { + return S().useCallback(a, b); + }; + exports.useContext = function(a, b) { + return S().useContext(a, b); + }; + exports.useDebugValue = function() {}; + exports.useEffect = function(a, b) { + return S().useEffect(a, b); + }; + exports.useImperativeHandle = function(a, b, c) { + return S().useImperativeHandle(a, b, c); + }; + exports.useLayoutEffect = function(a, b) { + return S().useLayoutEffect(a, b); + }; + exports.useMemo = function(a, b) { + return S().useMemo(a, b); + }; + exports.useReducer = function(a, b, c) { + return S().useReducer(a, b, c); + }; + exports.useRef = function(a) { + return S().useRef(a); + }; + exports.useState = function(a) { + return S().useState(a); + }; + exports.version = "17.0.2"; +}); +var load2 = __swcpack_require__.bind(void 0, function(module, exports) { + /** @license React v17.0.2 + * react.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ 'use strict'; + if (process.env.NODE_ENV !== "production") (function() { + 'use strict'; + var _assign = load(); + // TODO: this is special because it gets imported during build. + var ReactVersion = '17.0.2'; + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. If there is no native Symbol + // nor polyfill, then a plain number is used for performance. + var REACT_ELEMENT_TYPE = 0xeac7; + var REACT_PORTAL_TYPE = 0xeaca; + exports.Fragment = 0xeacb; + exports.StrictMode = 0xeacc; + exports.Profiler = 0xead2; + var REACT_PROVIDER_TYPE = 0xeacd; + var REACT_CONTEXT_TYPE = 0xeace; + var REACT_FORWARD_REF_TYPE = 0xead0; + exports.Suspense = 0xead1; + var REACT_SUSPENSE_LIST_TYPE = 0xead8; + var REACT_MEMO_TYPE = 0xead3; + var REACT_LAZY_TYPE = 0xead4; + var REACT_BLOCK_TYPE = 0xead9; + var REACT_SERVER_BLOCK_TYPE = 0xeada; + var REACT_FUNDAMENTAL_TYPE = 0xead5; + var REACT_SCOPE_TYPE = 0xead7; + var REACT_OPAQUE_ID_TYPE = 0xeae0; + var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; + var REACT_OFFSCREEN_TYPE = 0xeae2; + var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + exports.Fragment = symbolFor('react.fragment'); + exports.StrictMode = symbolFor('react.strict_mode'); + exports.Profiler = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + exports.Suspense = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + REACT_SCOPE_TYPE = symbolFor('react.scope'); + REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); + } + var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') return null; + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === 'function') return maybeIterator; + return null; + } + /** + * Keeps track of the current dispatcher. + */ var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ current: null + }; + /** + * Keeps track of the current batch's configuration such as how long an update + * should suspend for if it needs to. + */ var ReactCurrentBatchConfig = { + transition: 0 + }; + /** + * Keeps track of the current owner. + * + * The current owner is the component who should own any components that are + * currently being constructed. + */ var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ current: null + }; + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + currentExtraStackFrame = stack; + } + ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { + currentExtraStackFrame = stack; + }; // Stack implementation injected by the current renderer. + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFrame.getStackAddendum = function() { + var stack = ''; // Add an extra top frame while an element is being validated + if (currentExtraStackFrame) stack += currentExtraStackFrame; + // Delegate to the injected renderer-specific implementation + var impl = ReactDebugCurrentFrame.getCurrentStack; + if (impl) stack += impl() || ''; + return stack; + }; + /** + * Used by act() to track whether you're inside an act() scope. + */ var IsSomeRendererActing = { + current: false + }; + var ReactSharedInternals = { + ReactCurrentDispatcher: ReactCurrentDispatcher, + ReactCurrentBatchConfig: ReactCurrentBatchConfig, + ReactCurrentOwner: ReactCurrentOwner, + IsSomeRendererActing: IsSomeRendererActing, + // Used by renderers to avoid bundling object-assign twice in UMD bundles: + assign: _assign + }; + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + // by calls to these methods by a Babel plugin. + // + // In PROD (or in packages without access to React internals), + // they are left as they are instead. + function warn(format) { + for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)args[_key - 1] = arguments[_key]; + printWarning('warn', format, args); + } + function error(format) { + for(var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++)args[_key2 - 1] = arguments[_key2]; + printWarning('error', format, args); + } + function printWarning(level, format, args) { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + if (stack !== '') { + format += '%s'; + args = args.concat([ + stack + ]); + } + var argsWithFormat = args.map(function(item) { + return '' + item; + }); // Careful: RN currently depends on this prefix + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + var didWarnStateUpdateForUnmountedComponent = {}; + function warnNoop(publicInstance, callerName) { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; + var warningKey = componentName + "." + callerName; + if (didWarnStateUpdateForUnmountedComponent[warningKey]) return; + error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + /** + * This is the abstract API for an update queue. + */ var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ isMounted: function(publicInstance) { + return false; + }, + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ enqueueForceUpdate: function(publicInstance, callback, callerName) { + warnNoop(publicInstance, 'forceUpdate'); + }, + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, 'replaceState'); + }, + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ enqueueSetState: function(publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, 'setState'); + } + }; + var emptyObject = {}; + Object.freeze(emptyObject); + /** + * Base class helpers for the updating state of a component. + */ function Component(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the + // renderer. + this.updater = updater || ReactNoopUpdateQueue; + } + Component.prototype.isReactComponent = {}; + /** + * Sets a subset of the state. Always use this to mutate + * state. You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * + * When a function is provided to setState, it will be called at some point in + * the future (not synchronously). It will be called with the up to date + * component arguments (state, props, context). These values can be different + * from this.* because your function may be called after receiveProps but before + * shouldComponentUpdate, and this new state, props, and context will not yet be + * assigned to this. + * + * @param {object|function} partialState Next partial state or function to + * produce next partial state to be merged with current state. + * @param {?function} callback Called after state is updated. + * @final + * @protected + */ Component.prototype.setState = function(partialState, callback) { + if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); + this.updater.enqueueSetState(this, partialState, callback, 'setState'); + }; + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {?function} callback Called after update is complete. + * @final + * @protected + */ Component.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); + }; + var deprecatedAPIs = { + isMounted: [ + 'isMounted', + "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks." + ], + replaceState: [ + 'replaceState', + "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)." + ] + }; + var defineDeprecationWarning = function(methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function() { + warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); + return undefined; + } + }); + }; + for(var fnName in deprecatedAPIs)if (deprecatedAPIs.hasOwnProperty(fnName)) defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + function ComponentDummy() {} + ComponentDummy.prototype = Component.prototype; + /** + * Convenience component with default shallow equality check for sCU. + */ function PureComponent(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. + _assign(pureComponentPrototype, Component.prototype); + pureComponentPrototype.isPureReactComponent = true; + // an immutable object with a single mutable value + function createRef() { + var refObject = { + current: null + }; + Object.seal(refObject); + return refObject; + } + function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); + } + function getContextName(type) { + return type.displayName || 'Context'; + } + function getComponentName(type) { + if (type == null) // Host root, text node or just invalid type. + return null; + if (typeof type.tag === 'number') error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."); + if (typeof type === 'function') return type.displayName || type.name || null; + if (typeof type === 'string') return type; + switch(type){ + case exports.Fragment: + return 'Fragment'; + case REACT_PORTAL_TYPE: + return 'Portal'; + case exports.Profiler: + return 'Profiler'; + case exports.StrictMode: + return 'StrictMode'; + case exports.Suspense: + return 'Suspense'; + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + if (typeof type === 'object') switch(type.$$typeof){ + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + case REACT_MEMO_TYPE: + return getComponentName(type.type); + case REACT_BLOCK_TYPE: + return getComponentName(type._render); + case REACT_LAZY_TYPE: + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentName(init(payload)); + } catch (x) { + return null; + } + } + return null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + didWarnAboutStringRefs = {}; + function hasValidRef(config) { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + if (getter && getter.isReactWarning) return false; + } + return config.ref !== undefined; + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + if (getter && getter.isReactWarning) return false; + } + return config.key !== undefined; + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function() { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function() { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } + function warnIfStringRefCannotBeAutoConverted(config) { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentName(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + /** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ var ReactElement = function(type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + return element; + }; + /** + * Create and return a new ReactElement of the given type. + * See https://reactjs.org/docs/react-api.html#createelement + */ function createElement(type, config, children) { + var propName; // Reserved names are extracted + var props = {}; + var key = null; + var ref = null; + var self = null; + var source = null; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config); + } + if (hasValidKey(config)) key = '' + config.key; + self = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object + for(propName in config)if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) props[propName] = config[propName]; + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + var childrenLength = arguments.length - 2; + if (childrenLength === 1) props.children = children; + else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for(var i = 0; i < childrenLength; i++)childArray[i] = arguments[i + 2]; + if (Object.freeze) Object.freeze(childArray); + props.children = childArray; + } // Resolve default props + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for(propName in defaultProps)if (props[propName] === undefined) props[propName] = defaultProps[propName]; + } + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + if (key) defineKeyPropWarningGetter(props, displayName); + if (ref) defineRefPropWarningGetter(props, displayName); + } + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + /** + * Clone and return a new ReactElement using element as the starting point. + * See https://reactjs.org/docs/react-api.html#cloneelement + */ function cloneElement(element, config, children) { + if (!!(element === null || element === undefined)) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + var propName; // Original props are copied + var props = _assign({}, element.props); // Reserved names are extracted + var key = element.key; + var ref = element.ref; // Self is preserved since the owner is preserved. + var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a + // transpiler, and the original source is probably a better indicator of the + // true owner. + var source = element._source; // Owner will be preserved, unless ref is overridden + var owner = element._owner; + if (config != null) { + if (hasValidRef(config)) { + // Silently steal the ref from the parent. + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (hasValidKey(config)) key = '' + config.key; + // Remaining properties override existing props + var defaultProps; + if (element.type && element.type.defaultProps) defaultProps = element.type.defaultProps; + for(propName in config)if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === undefined && defaultProps !== undefined) // Resolve default props + props[propName] = defaultProps[propName]; + else props[propName] = config[propName]; + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + var childrenLength = arguments.length - 2; + if (childrenLength === 1) props.children = children; + else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for(var i = 0; i < childrenLength; i++)childArray[i] = arguments[i + 2]; + props.children = childArray; + } + return ReactElement(element.type, key, ref, self, source, owner, props); + } + /** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ function isValidElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + var SEPARATOR = '.'; + var SUBSEPARATOR = ':'; + /** + * Escape and wrap key so it is safe to use as a reactid + * + * @param {string} key to be escaped. + * @return {string} the escaped key. + */ function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + '=': '=0', + ':': '=2' + }; + var escapedString = key.replace(escapeRegex, function(match) { + return escaperLookup[match]; + }); + return '$' + escapedString; + } + /** + * TODO: Test that a single child and an array with one item have the same key + * pattern. + */ var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, '$&/'); + } + /** + * Generate a key string that identifies a element within a set. + * + * @param {*} element A element that could contain a manual key. + * @param {number} index Index that is used if a manual key is not provided. + * @return {string} + */ function getElementKey(element, index) { + // Do some typechecking here since we call this blindly. We want to ensure + // that we don't block potential future ES APIs. + if (typeof element === 'object' && element !== null && element.key != null) // Explicit key + return escape('' + element.key); + // Implicit key determined by the index in the set + return index.toString(36); + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if (type === 'undefined' || type === 'boolean') // All of the above are perceived as null. + children = null; + var invokeCallback = false; + if (children === null) invokeCallback = true; + else switch(type){ + case 'string': + case 'number': + invokeCallback = true; + break; + case 'object': + switch(children.$$typeof){ + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + } + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array + // so that it's consistent if the number of children grows: + var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + if (Array.isArray(mappedChild)) { + var escapedChildKey = ''; + if (childKey != null) escapedChildKey = escapeUserProvidedKey(childKey) + '/'; + mapIntoArray(mappedChild, array, escapedChildKey, '', function(c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) mappedChild = cloneAndReplaceKey(mappedChild, // traverseAllChildren used to do for objects as children + escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); + array.push(mappedChild); + } + return 1; + } + var child; + var nextName; + var subtreeCount = 0; // Count of children found in the current subtree. + var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (Array.isArray(children)) for(var i = 0; i < children.length; i++){ + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === 'function') { + var iterableChildren = children; + // Warn about using Maps as children + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + didWarnAboutMaps = true; + } + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + while(!(step = iterator.next()).done){ + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === 'object') { + var childrenString = '' + children; + throw Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). If you meant to render a collection of children, use an array instead."); + } + } + return subtreeCount; + } + /** + * Maps children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenmap + * + * The provided mapFunction(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} func The map function. + * @param {*} context Context for mapFunction. + * @return {object} Object containing the ordered map of results. + */ function mapChildren(children, func, context) { + if (children == null) return children; + var result = []; + var count = 0; + mapIntoArray(children, result, '', '', function(child) { + return func.call(context, child, count++); + }); + return result; + } + /** + * Count the number of children that are typically specified as + * `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrencount + * + * @param {?*} children Children tree container. + * @return {number} The number of children. + */ function countChildren(children) { + var n = 0; + mapChildren(children, function() { + n++; // Don't return anything + }); + return n; + } + /** + * Iterates through children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenforeach + * + * The provided forEachFunc(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} forEachFunc + * @param {*} forEachContext Context for forEachContext. + */ function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function() { + forEachFunc.apply(this, arguments); // Don't return anything. + }, forEachContext); + } + /** + * Flatten a children object (typically specified as `props.children`) and + * return an array with appropriately re-keyed children. + * + * See https://reactjs.org/docs/react-api.html#reactchildrentoarray + */ function toArray(children) { + return mapChildren(children, function(child) { + return child; + }) || []; + } + /** + * Returns the first child in a collection of children and verifies that there + * is only one child in the collection. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenonly + * + * The current implementation of this function assumes that a single child gets + * passed without a wrapper, but the purpose of this helper function is to + * abstract away the particular structure of children. + * + * @param {?object} children Child collection structure. + * @return {ReactElement} The first and only `ReactElement` contained in the + * structure. + */ function onlyChild(children) { + if (!isValidElement(children)) throw Error("React.Children.only expected to receive a single React element child."); + return children; + } + function createContext(defaultValue, calculateChangedBits) { + if (calculateChangedBits === undefined) calculateChangedBits = null; + else if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') error("createContext: Expected the optional second argument to be a function. Instead received: %s", calculateChangedBits); + var context = { + $$typeof: REACT_CONTEXT_TYPE, + _calculateChangedBits: calculateChangedBits, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + // A separate object, but proxies back to the original context object for + // backwards compatibility. It has a different $$typeof, so we can properly + // warn for the incorrect usage of Context as a Consumer. + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context, + _calculateChangedBits: context._calculateChangedBits + }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here + Object.defineProperties(Consumer, { + Provider: { + get: function() { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context.Provider; + }, + set: function(_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function() { + return context._currentValue; + }, + set: function(_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function() { + return context._currentValue2; + }, + set: function(_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function() { + return context._threadCount; + }, + set: function(_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function() { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context.Consumer; + } + }, + displayName: { + get: function() { + return context.displayName; + }, + set: function(displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty + context.Consumer = Consumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + return context; + } + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); // Transition to the next state. + var pending = payload; + pending._status = Pending; + pending._result = thenable; + thenable.then(function(moduleObject) { + if (payload._status === Pending) { + var defaultExport = moduleObject.default; + if (defaultExport === undefined) error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + var resolved = payload; + resolved._status = Resolved; + resolved._result = defaultExport; + } + }, function(error) { + if (payload._status === Pending) { + // Transition to the next state. + var rejected = payload; + rejected._status = Rejected; + rejected._result = error; + } + }); + } + if (payload._status === Resolved) return payload._result; + else throw payload._result; + } + function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: -1, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + // In production, this would just set it on the object. + var defaultProps; + var propTypes; // $FlowFixMe + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function() { + return defaultProps; + }, + set: function(newDefaultProps) { + error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + defaultProps = newDefaultProps; // Match production behavior more closely: + // $FlowFixMe + Object.defineProperty(lazyType, 'defaultProps', { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function() { + return propTypes; + }, + set: function(newPropTypes) { + error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + propTypes = newPropTypes; // Match production behavior more closely: + // $FlowFixMe + Object.defineProperty(lazyType, 'propTypes', { + enumerable: true + }); + } + } + }); + return lazyType; + } + function forwardRef(render) { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); + else if (typeof render !== 'function') error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); + else if (render.length !== 0 && render.length !== 2) error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); + } + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: render + }; + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (render.displayName == null) render.displayName = name; + } + }); + return elementType; + } + // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. + var enableScopeAPI = false; // Experimental Create Event Handle API. + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') return true; + // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) return true; + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) return true; + } + return false; + } + function memo(type, compare) { + if (!isValidElementType(type)) error("memo: The first argument must be a component. Instead received: %s", type === null ? 'null' : typeof type); + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: compare === undefined ? null : compare + }; + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (type.displayName == null) type.displayName = name; + } + }); + return elementType; + } + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + if (!(dispatcher !== null)) throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + return dispatcher; + } + function useContext(Context, unstable_observedBits) { + var dispatcher = resolveDispatcher(); + if (unstable_observedBits !== undefined) error("useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" : ''); + // TODO: add a more generic warning for invalid values. + if (Context._context !== undefined) { + var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs + // and nobody should be using this in existing code. + if (realContext.Consumer === Context) error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); + else if (realContext.Provider === Context) error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); + } + return dispatcher.useContext(Context, unstable_observedBits); + } + function useState(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() {} + disabledLog.__reactDisabledLog = true; + function disableLogs() { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ } + disabledDepth++; + } + function reenableLogs() { + disabledDepth--; + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + Object.defineProperties(console, { + log: _assign({}, props, { + value: prevLog + }), + info: _assign({}, props, { + value: prevInfo + }), + warn: _assign({}, props, { + value: prevWarn + }), + error: _assign({}, props, { + value: prevError + }), + group: _assign({}, props, { + value: prevGroup + }), + groupCollapsed: _assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: _assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ } + if (disabledDepth < 0) error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + if (prefix === undefined) // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + // We use the prefix to ensure our stacks line up with native stack frames. + return '\n' + prefix + name; + } + var reentry = false; + var componentFrameCache; + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) return ''; + var frame = componentFrameCache.get(fn); + if (frame !== undefined) return frame; + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + Error.prepareStackTrace = undefined; + var previousDispatcher; + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + ReactCurrentDispatcher$1.current = null; + disableLogs(); + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function() { + throw Error(); + }; // $FlowFixMe + Object.defineProperty(Fake.prototype, 'props', { + set: function() { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while(s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c])// We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + for(; s >= 1 && c >= 0; s--, c--)// Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); + if (typeof fn === 'function') componentFrameCache.set(fn, _frame); + return _frame; + } + }while (s >= 1 && c >= 0) + break; + } + } + } finally{ + reentry = false; + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + if (typeof fn === 'function') componentFrameCache.set(fn, syntheticFrame); + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + return describeNativeComponentFrame(fn, false); + } + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) return ''; + if (typeof type === 'function') return describeNativeComponentFrame(type, shouldConstruct(type)); + if (typeof type === 'string') return describeBuiltInComponentFrame(type); + switch(type){ + case exports.Suspense: + return describeBuiltInComponentFrame('Suspense'); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + if (typeof type === 'object') switch(type.$$typeof){ + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_BLOCK_TYPE: + return describeFunctionComponentFrame(type._render); + case REACT_LAZY_TYPE: + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + return ''; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(Object.prototype.hasOwnProperty); + for(var typeSpecName in typeSpecs)if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || 'React class', location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error('Failed %s type: %s', location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + function setCurrentlyValidatingElement$1(element) { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else setExtraStackFrame(null); + } + var propTypesMisspellWarningShown; + propTypesMisspellWarningShown = false; + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentName(ReactCurrentOwner.current.type); + if (name) return '\n\nCheck the render method of `' + name + '`.'; + } + return ''; + } + function getSourceInfoErrorAddendum(source) { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + return ''; + } + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== undefined) return getSourceInfoErrorAddendum(elementProps.__source); + return ''; + } + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + if (parentName) info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + return info; + } + /** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) return; + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) return; + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + var childOwner = ''; + if (element && element._owner && element._owner !== ReactCurrentOwner.current) // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + /** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ function validateChildKeys(node, parentType) { + if (typeof node !== 'object') return; + if (Array.isArray(node)) for(var i = 0; i < node.length; i++){ + var child = node[i]; + if (isValidElement(child)) validateExplicitKey(child, parentType); + } + else if (isValidElement(node)) // This element was passed in a valid location. + { + if (node._store) node._store.validated = true; + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === 'function') // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while(!(step = iterator.next()).done)if (isValidElement(step.value)) validateExplicitKey(step.value, parentType); + } + } + } + } + /** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ function validatePropTypes(element) { + var type = element.type; + if (type === null || type === undefined || typeof type === 'string') return; + var propTypes; + if (typeof type === 'function') propTypes = type.propTypes; + else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) propTypes = type.propTypes; + else return; + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentName(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + var _name = getComponentName(type); + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + /** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ function validateFragmentProps(fragment) { + var keys = Object.keys(fragment.props); + for(var i = 0; i < keys.length; i++){ + var key = keys[i]; + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + setCurrentlyValidatingElement$1(null); + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + if (!validType) { + var info = ''; + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + if (sourceInfo) info += sourceInfo; + else info += getDeclarationErrorAddendum(); + var typeString; + if (type === null) typeString = 'null'; + else if (Array.isArray(type)) typeString = 'array'; + else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else typeString = typeof type; + error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + if (element == null) return element; + // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + if (validType) for(var i = 2; i < arguments.length; i++)validateChildKeys(arguments[i], type); + if (type === exports.Fragment) validateFragmentProps(element); + else validatePropTypes(element); + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); + } // Legacy hook: remove it + Object.defineProperty(validatedFactory, 'type', { + enumerable: false, + get: function() { + warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); + Object.defineProperty(this, 'type', { + value: type + }); + return type; + } + }); + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + for(var i = 2; i < arguments.length; i++)validateChildKeys(arguments[i], newElement.type); + validatePropTypes(newElement); + return newElement; + } + try { + var frozenObject = Object.freeze({}); + /* eslint-disable no-new */ new Map([ + [ + frozenObject, + null + ] + ]); + new Set([ + frozenObject + ]); + /* eslint-enable no-new */ } catch (e) {} + var createElement$1 = createElementWithValidation; + var cloneElement$1 = cloneElementWithValidation; + var createFactory = createFactoryWithValidation; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray: toArray, + only: onlyChild + }; + exports.Children = Children; + exports.Component = Component; + exports.PureComponent = PureComponent; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext; + exports.createElement = createElement$1; + exports.createFactory = createFactory; + exports.createRef = createRef; + exports.forwardRef = forwardRef; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.useCallback = useCallback; + exports.useContext = useContext; + exports.useDebugValue = useDebugValue; + exports.useEffect = useEffect; + exports.useImperativeHandle = useImperativeHandle; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo; + exports.useReducer = useReducer; + exports.useRef = useRef; + exports.useState = useState; + exports.version = ReactVersion; + })(); +}); +var load3 = __swcpack_require__.bind(void 0, function(module, exports) { + 'use strict'; + if (process.env.NODE_ENV === 'production') module.exports = load1(); + else module.exports = load2(); +}); +var load4 = __swcpack_require__.bind(void 0, function(module, exports) { + /** @license React v17.0.2 + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ 'use strict'; + load(); + var f = load3(), g = 60103; + exports.Fragment = 60107; + if ("function" === typeof Symbol && Symbol.for) { + var h = Symbol.for; + g = h("react.element"); + exports.Fragment = h("react.fragment"); + } + var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { + key: !0, + ref: !0, + __self: !0, + __source: !0 + }; + function q(c, a, k) { + var b, d = {}, e = null, l = null; + void 0 !== k && (e = "" + k); + void 0 !== a.key && (e = "" + a.key); + void 0 !== a.ref && (l = a.ref); + for(b in a)n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); + if (c && c.defaultProps) for(b in a = c.defaultProps, a)void 0 === d[b] && (d[b] = a[b]); + return { + $$typeof: g, + type: c, + key: e, + ref: l, + props: d, + _owner: m.current + }; + } + exports.jsx = q; + exports.jsxs = q; +}); +var load5 = __swcpack_require__.bind(void 0, function(module, exports) { + /** @license React v17.0.2 + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ 'use strict'; + if (process.env.NODE_ENV !== "production") (function() { + 'use strict'; + var React = load3(); + var _assign = load(); + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. If there is no native Symbol + // nor polyfill, then a plain number is used for performance. + var REACT_ELEMENT_TYPE = 0xeac7; + var REACT_PORTAL_TYPE = 0xeaca; + exports.Fragment = 0xeacb; + var REACT_STRICT_MODE_TYPE = 0xeacc; + var REACT_PROFILER_TYPE = 0xead2; + var REACT_PROVIDER_TYPE = 0xeacd; + var REACT_CONTEXT_TYPE = 0xeace; + var REACT_FORWARD_REF_TYPE = 0xead0; + var REACT_SUSPENSE_TYPE = 0xead1; + var REACT_SUSPENSE_LIST_TYPE = 0xead8; + var REACT_MEMO_TYPE = 0xead3; + var REACT_LAZY_TYPE = 0xead4; + var REACT_BLOCK_TYPE = 0xead9; + var REACT_SERVER_BLOCK_TYPE = 0xeada; + var REACT_FUNDAMENTAL_TYPE = 0xead5; + var REACT_SCOPE_TYPE = 0xead7; + var REACT_OPAQUE_ID_TYPE = 0xeae0; + var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; + var REACT_OFFSCREEN_TYPE = 0xeae2; + var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + exports.Fragment = symbolFor('react.fragment'); + REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); + REACT_PROFILER_TYPE = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + REACT_SCOPE_TYPE = symbolFor('react.scope'); + REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); + } + var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') return null; + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === 'function') return maybeIterator; + return null; + } + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function error(format) { + for(var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++)args[_key2 - 1] = arguments[_key2]; + printWarning('error', format, args); + } + function printWarning(level, format, args) { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + if (stack !== '') { + format += '%s'; + args = args.concat([ + stack + ]); + } + var argsWithFormat = args.map(function(item) { + return '' + item; + }); // Careful: RN currently depends on this prefix + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. + var enableScopeAPI = false; // Experimental Create Event Handle API. + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') return true; + // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) return true; + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) return true; + } + return false; + } + function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); + } + function getContextName(type) { + return type.displayName || 'Context'; + } + function getComponentName(type) { + if (type == null) // Host root, text node or just invalid type. + return null; + if (typeof type.tag === 'number') error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."); + if (typeof type === 'function') return type.displayName || type.name || null; + if (typeof type === 'string') return type; + switch(type){ + case exports.Fragment: + return 'Fragment'; + case REACT_PORTAL_TYPE: + return 'Portal'; + case REACT_PROFILER_TYPE: + return 'Profiler'; + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + if (typeof type === 'object') switch(type.$$typeof){ + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + case REACT_MEMO_TYPE: + return getComponentName(type.type); + case REACT_BLOCK_TYPE: + return getComponentName(type._render); + case REACT_LAZY_TYPE: + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentName(init(payload)); + } catch (x) { + return null; + } + } + return null; + } + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() {} + disabledLog.__reactDisabledLog = true; + function disableLogs() { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ } + disabledDepth++; + } + function reenableLogs() { + disabledDepth--; + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + Object.defineProperties(console, { + log: _assign({}, props, { + value: prevLog + }), + info: _assign({}, props, { + value: prevInfo + }), + warn: _assign({}, props, { + value: prevWarn + }), + error: _assign({}, props, { + value: prevError + }), + group: _assign({}, props, { + value: prevGroup + }), + groupCollapsed: _assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: _assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ } + if (disabledDepth < 0) error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + if (prefix === undefined) // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + // We use the prefix to ensure our stacks line up with native stack frames. + return '\n' + prefix + name; + } + var reentry = false; + var componentFrameCache; + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) return ''; + var frame = componentFrameCache.get(fn); + if (frame !== undefined) return frame; + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + Error.prepareStackTrace = undefined; + var previousDispatcher; + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + ReactCurrentDispatcher.current = null; + disableLogs(); + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function() { + throw Error(); + }; // $FlowFixMe + Object.defineProperty(Fake.prototype, 'props', { + set: function() { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while(s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c])// We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + for(; s >= 1 && c >= 0; s--, c--)// Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); + if (typeof fn === 'function') componentFrameCache.set(fn, _frame); + return _frame; + } + }while (s >= 1 && c >= 0) + break; + } + } + } finally{ + reentry = false; + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + if (typeof fn === 'function') componentFrameCache.set(fn, syntheticFrame); + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + return describeNativeComponentFrame(fn, false); + } + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) return ''; + if (typeof type === 'function') return describeNativeComponentFrame(type, shouldConstruct(type)); + if (typeof type === 'string') return describeBuiltInComponentFrame(type); + switch(type){ + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + if (typeof type === 'object') switch(type.$$typeof){ + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_BLOCK_TYPE: + return describeFunctionComponentFrame(type._render); + case REACT_LAZY_TYPE: + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + return ''; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else ReactDebugCurrentFrame.setExtraStackFrame(null); + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(Object.prototype.hasOwnProperty); + for(var typeSpecName in typeSpecs)if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || 'React class', location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error('Failed %s type: %s', location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown; + var specialPropRefWarningShown; + var didWarnAboutStringRefs; + didWarnAboutStringRefs = {}; + function hasValidRef(config) { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + if (getter && getter.isReactWarning) return false; + } + return config.ref !== undefined; + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + if (getter && getter.isReactWarning) return false; + } + return config.key !== undefined; + } + function warnIfStringRefCannotBeAutoConverted(config, self) { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { + var componentName = getComponentName(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function() { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function() { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } + /** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ var ReactElement = function(type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + return element; + }; + /** + * https://github.com/reactjs/rfcs/pull/107 + * @param {*} type + * @param {object} props + * @param {string} key + */ function jsxDEV(type, config, maybeKey, source, self) { + var propName; // Reserved names are extracted + var props = {}; + var key = null; + var ref = null; // Currently, key can be spread in as a prop. This causes a potential + // issue if key is also explicitly declared (ie.

+ // or
). We want to deprecate key spread, + // but as an intermediary step, we will use jsxDEV for everything except + //
, because we aren't currently able to tell if + // key is explicitly declared to be undefined or not. + if (maybeKey !== undefined) key = '' + maybeKey; + if (hasValidKey(config)) key = '' + config.key; + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self); + } // Remaining properties are added to a new props object + for(propName in config)if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) props[propName] = config[propName]; + // Resolve default props + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for(propName in defaultProps)if (props[propName] === undefined) props[propName] = defaultProps[propName]; + } + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + if (key) defineKeyPropWarningGetter(props, displayName); + if (ref) defineRefPropWarningGetter(props, displayName); + } + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement$1(element) { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + var propTypesMisspellWarningShown; + propTypesMisspellWarningShown = false; + /** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ function isValidElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner$1.current) { + var name = getComponentName(ReactCurrentOwner$1.current.type); + if (name) return '\n\nCheck the render method of `' + name + '`.'; + } + return ''; + } + function getSourceInfoErrorAddendum(source) { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + return ''; + } + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + if (parentName) info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + return info; + } + /** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) return; + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) return; + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + var childOwner = ''; + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + /** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ function validateChildKeys(node, parentType) { + if (typeof node !== 'object') return; + if (Array.isArray(node)) for(var i = 0; i < node.length; i++){ + var child = node[i]; + if (isValidElement(child)) validateExplicitKey(child, parentType); + } + else if (isValidElement(node)) // This element was passed in a valid location. + { + if (node._store) node._store.validated = true; + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === 'function') // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while(!(step = iterator.next()).done)if (isValidElement(step.value)) validateExplicitKey(step.value, parentType); + } + } + } + } + /** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ function validatePropTypes(element) { + var type = element.type; + if (type === null || type === undefined || typeof type === 'string') return; + var propTypes; + if (typeof type === 'function') propTypes = type.propTypes; + else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) propTypes = type.propTypes; + else return; + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentName(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + var _name = getComponentName(type); + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + /** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ function validateFragmentProps(fragment) { + var keys = Object.keys(fragment.props); + for(var i = 0; i < keys.length; i++){ + var key = keys[i]; + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + setCurrentlyValidatingElement$1(null); + } + } + function jsxWithValidation(type, props, key, isStaticChildren, source, self) { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + if (!validType) { + var info = ''; + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + var sourceInfo = getSourceInfoErrorAddendum(source); + if (sourceInfo) info += sourceInfo; + else info += getDeclarationErrorAddendum(); + var typeString; + if (type === null) typeString = 'null'; + else if (Array.isArray(type)) typeString = 'array'; + else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else typeString = typeof type; + error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + if (element == null) return element; + // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + if (validType) { + var children = props.children; + if (children !== undefined) { + if (isStaticChildren) { + if (Array.isArray(children)) { + for(var i = 0; i < children.length; i++)validateChildKeys(children[i], type); + if (Object.freeze) Object.freeze(children); + } else error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); + } else validateChildKeys(children, type); + } + } + if (type === exports.Fragment) validateFragmentProps(element); + else validatePropTypes(element); + return element; + } // These two functions exist to still get child warnings in dev + // even with the prod transform. This means that jsxDEV is purely + // opt-in behavior for better messages but that we won't stop + // giving you warnings if you use production apis. + function jsxWithValidationStatic(type, props, key) { + return jsxWithValidation(type, props, key, true); + } + function jsxWithValidationDynamic(type, props, key) { + return jsxWithValidation(type, props, key, false); + } + var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children. + // for now we can ship identical prod functions + var jsxs = jsxWithValidationStatic; + exports.jsx = jsx; + exports.jsxs = jsxs; + })(); +}); +var load6 = __swcpack_require__.bind(void 0, function(module, exports) { + 'use strict'; + if (process.env.NODE_ENV === 'production') module.exports = load4(); + else module.exports = load5(); +}); +var { jsx: _jsx } = load6(); +var Divider = _jsx("div", {}); export { Divider as Divider }; diff --git a/crates/swc_node_comments/src/lib.rs b/crates/swc_node_comments/src/lib.rs index 417f00bf161a..6d8d9f054cc4 100644 --- a/crates/swc_node_comments/src/lib.rs +++ b/crates/swc_node_comments/src/lib.rs @@ -157,4 +157,17 @@ impl Comments for SwcComments { false }) } + + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + for comments in self.leading.iter() { + for comment in comments.value() { + f(comment); + } + } + for comments in self.trailing.iter() { + for comment in comments.value() { + f(comment); + } + } + } } diff --git a/crates/swc_plugin_proxy/src/comments/plugin_comments_proxy.rs b/crates/swc_plugin_proxy/src/comments/plugin_comments_proxy.rs index 78759222fdcf..d4143d3a1441 100644 --- a/crates/swc_plugin_proxy/src/comments/plugin_comments_proxy.rs +++ b/crates/swc_plugin_proxy/src/comments/plugin_comments_proxy.rs @@ -150,6 +150,12 @@ impl Comments for PluginCommentsProxy { c.add_pure_comment(pos); }); } + + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + swc_common::comments::COMMENTS.with(|c| { + c.for_each(f); + }); + } } #[cfg(all(feature = "__plugin_mode", target_arch = "wasm32"))] @@ -276,4 +282,8 @@ impl Comments for PluginCommentsProxy { } } } + + fn for_each(&self, f: &mut dyn FnMut(&Comment)) { + unimplemented!() + } } diff --git a/crates/swc_ts_fast_strip/src/lib.rs b/crates/swc_ts_fast_strip/src/lib.rs index 797a6673a2d7..2eec5def7da6 100644 --- a/crates/swc_ts_fast_strip/src/lib.rs +++ b/crates/swc_ts_fast_strip/src/lib.rs @@ -415,6 +415,49 @@ pub fn operate( let top_level_mark = Mark::new(); HELPERS.set(&Helpers::new(false), || { + let transform = options.transform.unwrap_or_default(); + + #[cfg(feature = "nightly")] + let mut jsx_pass = { + let (mut before_resolver_jsx, after_resolver_jsx) = + swc_ecma_transforms_react::jsx( + cm.clone(), + Some(comments.clone()), + swc_ecma_transforms_react::Options { + runtime: match &transform.jsx { + Some(jsx_config) => { + let import_source = + jsx_config.import_source.clone().unwrap_or_else( + swc_ecma_transforms_react::default_import_source, + ); + swc_ecma_transforms_react::Runtime::Automatic( + swc_ecma_transforms_react::AutomaticConfig { + import_source, + }, + ) + } + None => swc_ecma_transforms_react::Runtime::Automatic( + Default::default(), + ), + }, + common: swc_ecma_transforms_react::CommonConfig { + development: transform + .jsx + .as_ref() + .and_then(|jsx| jsx.transform.as_ref()) + .map(|t| matches!(t, JsxTransform::ReactJsxDev)) + .unwrap_or(false) + .into(), + ..Default::default() + }, + refresh: None, + }, + unresolved_mark, + ); + program.mutate(&mut before_resolver_jsx); + after_resolver_jsx + }; + program.mutate(&mut resolver(unresolved_mark, top_level_mark, true)); if deprecated_ts_module_as_error { @@ -434,8 +477,6 @@ pub fn operate( } } - let transform = options.transform.unwrap_or_default(); - program.mutate(&mut typescript::typescript( transform.typescript, unresolved_mark, @@ -443,29 +484,7 @@ pub fn operate( )); #[cfg(feature = "nightly")] - program.mutate(&mut swc_ecma_transforms_react::jsx( - cm.clone(), - Some(comments.clone()), - swc_ecma_transforms_react::Options { - next: Some(true), - runtime: Some(swc_ecma_transforms_react::Runtime::Automatic), - import_source: transform - .jsx - .as_ref() - .and_then(|jsx| jsx.import_source.clone()), - development: match transform.jsx { - Some(JsxConfig { - transform: Some(transform), - .. - }) => Some(matches!(transform, JsxTransform::ReactJsxDev)), - _ => None, - }, - refresh: None, - ..Default::default() - }, - top_level_mark, - unresolved_mark, - )); + program.mutate(&mut jsx_pass); program.mutate(&mut inject_helpers(unresolved_mark)); diff --git a/packages/types/index.ts b/packages/types/index.ts index 0d39b8c07e00..a2c3d98e4dd3 100644 --- a/packages/types/index.ts +++ b/packages/types/index.ts @@ -836,14 +836,16 @@ export interface EsParserConfig { explicitResourceManagement?: boolean; } +type JSXPreset = "react" | "react-jsx" | "react-jsxdev" | "preserve" | "react-native"; + /** * Options for transform. */ export interface TransformConfig { /** - * Effective only if `syntax` supports ƒ. + * Effective only if `syntax` supports. */ - react?: ReactConfig; + react?: JSXPreset | ReactConfig; constModules?: ConstModulesConfig; @@ -947,7 +949,7 @@ export interface ReactConfig { /** * jsx runtime */ - runtime?: "automatic" | "classic"; + runtime?: "automatic" | "classic" | "preserve"; /** * Declares the module specifier to be used for importing the `jsx` and `jsxs` factory functions when using `runtime` 'automatic'