From cf40d73853fb2c820e0813621c6aac11c3fbe01b Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Thu, 14 Oct 2021 14:46:55 -0700 Subject: [PATCH] Fix React auto-import blocking component imports in --preserve --- src/services/codefixes/importFixes.ts | 6 +++- .../fourslash/importNameCodeFix_jsxReact17.ts | 31 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/importNameCodeFix_jsxReact17.ts diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 6fd9b702f04e6..d910128f6db86 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -766,9 +766,13 @@ namespace ts.codefix { return { fixes, symbolName }; } + function jsxModeNeedsExplicitImport(jsx: JsxEmit | undefined) { + return jsx === JsxEmit.React || jsx === JsxEmit.ReactNative; + } + function getSymbolName(sourceFile: SourceFile, checker: TypeChecker, symbolToken: Identifier, compilerOptions: CompilerOptions): string { const parent = symbolToken.parent; - if ((isJsxOpeningLikeElement(parent) || isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== JsxEmit.ReactJSX && compilerOptions.jsx !== JsxEmit.ReactJSXDev) { + if ((isJsxOpeningLikeElement(parent) || isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { const jsxNamespace = checker.getJsxNamespace(sourceFile); if (isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, SymbolFlags.Value, /*excludeGlobals*/ true)) { return jsxNamespace; diff --git a/tests/cases/fourslash/importNameCodeFix_jsxReact17.ts b/tests/cases/fourslash/importNameCodeFix_jsxReact17.ts new file mode 100644 index 0000000000000..9fa78d511138d --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFix_jsxReact17.ts @@ -0,0 +1,31 @@ +/// + +// @jsx: preserve +// @module: commonjs + +// @Filename: /node_modules/@types/react/index.d.ts +//// declare namespace React { +//// function createElement(): any; +//// } +//// export = React; +//// export as namespace React; +//// +//// declare global { +//// namespace JSX { +//// interface IntrinsicElements {} +//// interface IntrinsicAttributes {} +//// } +//// } + +// @Filename: /component.tsx +//// import "react"; +//// export declare function Component(): any; + +// @Filename: /index.tsx +//// (); + +goTo.marker(""); +verify.importFixAtPosition([`import { Component } from "./component"; + +();`]); +