Skip to content

Auto-include types for the jsx import source in the new jsx transforms #41330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 32 additions & 4 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25132,14 +25132,42 @@ namespace ts {
return links.resolvedSymbol;
}

function getJsxNamespaceContainerForImplicitImport(location: Node | undefined): Symbol | undefined {
const file = location && getSourceFileOfNode(location);
const links = file && getNodeLinks(file);
if (links && links.jsxImplicitImportContainer === false) {
return undefined;
}
if (links && links.jsxImplicitImportContainer) {
return links.jsxImplicitImportContainer;
}
const runtimeImportSpecifier = getJSXRuntimeImport(getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
if (!runtimeImportSpecifier) {
return undefined;
}
const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic;
const errorMessage = isClassic
? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
: Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
const mod = resolveExternalModule(location!, runtimeImportSpecifier, errorMessage, location!);
const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined;
if (links) {
links.jsxImplicitImportContainer = result || false;
}
return result;
}

function getJsxNamespaceAt(location: Node | undefined): Symbol {
const links = location && getNodeLinks(location);
if (links && links.jsxNamespace) {
return links.jsxNamespace;
}
if (!links || links.jsxNamespace !== false) {
const namespaceName = getJsxNamespace(location);
const resolvedNamespace = resolveName(location, namespaceName, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
let resolvedNamespace = resolveName(location, namespaceName, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
}
if (resolvedNamespace) {
const candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, SymbolFlags.Namespace));
if (candidate && candidate !== unknownSymbol) {
Expand All @@ -25148,9 +25176,9 @@ namespace ts {
}
return candidate;
}
if (links) {
links.jsxNamespace = false;
}
}
if (links) {
links.jsxNamespace = false;
}
}
// JSX global fallback
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ namespace ts {
type: jsxOptionMap,
affectsSourceFile: true,
affectsEmit: true,
affectsModuleResolution: true,
paramType: Diagnostics.KIND,
showInSimplifiedHelpView: true,
category: Diagnostics.Basic_Options,
Expand Down Expand Up @@ -802,6 +803,9 @@ namespace ts {
{
name: "jsxImportSource",
type: "string",
affectsSemanticDiagnostics: true,
affectsEmit: true,
affectsModuleResolution: true,
category: Diagnostics.Advanced_Options,
description: Diagnostics.Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react
},
Expand Down
28 changes: 19 additions & 9 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2201,6 +2201,15 @@ namespace ts {
: b.kind === SyntaxKind.StringLiteral && a.text === b.text;
}

function createSyntheticImport(text: string, file: SourceFile) {
const externalHelpersModuleReference = factory.createStringLiteral(text);
const importDecl = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
addEmitFlags(importDecl, EmitFlags.NeverApplyImportHelper);
setParent(externalHelpersModuleReference, importDecl);
setParent(importDecl, file);
return externalHelpersModuleReference;
}

function collectExternalModuleReferences(file: SourceFile): void {
if (file.imports) {
return;
Expand All @@ -2216,16 +2225,17 @@ namespace ts {

// If we are importing helpers, we need to add a synthetic reference to resolve the
// helpers library.
if (options.importHelpers
&& (options.isolatedModules || isExternalModuleFile)
if ((options.isolatedModules || isExternalModuleFile)
&& !file.isDeclarationFile) {
// synthesize 'import "tslib"' declaration
const externalHelpersModuleReference = factory.createStringLiteral(externalHelpersModuleNameText);
const importDecl = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
addEmitFlags(importDecl, EmitFlags.NeverApplyImportHelper);
setParent(externalHelpersModuleReference, importDecl);
setParent(importDecl, file);
imports = [externalHelpersModuleReference];
if (options.importHelpers) {
// synthesize 'import "tslib"' declaration
imports = [createSyntheticImport(externalHelpersModuleNameText, file)];
}
const jsxImport = getJSXRuntimeImport(getJSXImplicitImportBase(options, file), options);
if (jsxImport) {
// synthesize `import "base/jsx-runtime"` declaration
(imports ||= []).push(createSyntheticImport(jsxImport, file));
}
}

for (const node of file.statements) {
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/transformers/jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ namespace ts {
function getImplicitImportForName(name: string) {
const importSource = name === "createElement"
? currentFileState.importSpecifier!
: `${currentFileState.importSpecifier}/${compilerOptions.jsx === JsxEmit.ReactJSXDev ? "jsx-dev-runtime" : "jsx-runtime"}`;
: getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions)!;
const existing = currentFileState.utilizedImplicitRuntimeImports?.get(importSource)?.get(name);
if (existing) {
return existing.name;
Expand Down
1 change: 1 addition & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4843,6 +4843,7 @@ namespace ts {
resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference
switchTypes?: Type[]; // Cached array of switch case expression types
jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node
jsxImplicitImportContainer?: Symbol | false; // Resolved module symbol the implicit jsx import of this file should refer to
contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive
deferredNodes?: ESMap<NodeId, Node>; // Set of nodes whose checking has been deferred
capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement
Expand Down
8 changes: 6 additions & 2 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6009,8 +6009,8 @@ namespace ts {
return jsx === JsxEmit.React || jsx === JsxEmit.ReactJSX || jsx === JsxEmit.ReactJSXDev;
}

export function getJSXImplicitImportBase(compilerOptions: CompilerOptions, file: SourceFile): string | undefined {
const jsxImportSourcePragmas = file.pragmas.get("jsximportsource");
export function getJSXImplicitImportBase(compilerOptions: CompilerOptions, file?: SourceFile): string | undefined {
const jsxImportSourcePragmas = file?.pragmas.get("jsximportsource");
const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas;
return compilerOptions.jsx === JsxEmit.ReactJSX ||
compilerOptions.jsx === JsxEmit.ReactJSXDev ||
Expand All @@ -6020,6 +6020,10 @@ namespace ts {
undefined;
}

export function getJSXRuntimeImport(base: string | undefined, options: CompilerOptions) {
return base ? `${base}/${options.jsx === JsxEmit.ReactJSXDev ? "jsx-dev-runtime" : "jsx-runtime"}` : undefined;
}

export function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false;
for (let i = 0; i < str.length; i++) {
Expand Down
28 changes: 28 additions & 0 deletions src/testRunner/unittests/tscWatch/incremental.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,5 +276,33 @@ export interface A {
],
modifyFs: host => host.deleteFile(`${project}/globals.d.ts`)
});

const jsxImportSourceOptions = { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" };
const jsxLibraryContent = `export namespace JSX {
interface Element {}
interface IntrinsicElements {
div: {
propA?: boolean;
};
}
}
export function jsx(...args: any[]): void;
export function jsxs(...args: any[]): void;
export const Fragment: unique symbol;
`;

verifyIncrementalWatchEmit({
subScenario: "jsxImportSource option changed",
files: () => [
{ path: libFile.path, content: libContent },
{ path: `${project}/node_modules/react/jsx-runtime/index.d.ts`, content: jsxLibraryContent },
{ path: `${project}/node_modules/react/package.json`, content: JSON.stringify({ name: "react", version: "0.0.1" }) },
{ path: `${project}/node_modules/preact/jsx-runtime/index.d.ts`, content: jsxLibraryContent.replace("propA", "propB") },
{ path: `${project}/node_modules/preact/package.json`, content: JSON.stringify({ name: "preact", version: "0.0.1" }) },
{ path: `${project}/index.tsx`, content: `export const App = () => <div propA={true}></div>;` },
{ path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) }
],
modifyFs: host => host.writeFile(configFile.path, JSON.stringify({ compilerOptions: { ...jsxImportSourceOptions, jsxImportSource: "preact" } }))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add another case hen preact*.d.ts file is missing and added.
And another when it is present and as incremental change goes missing.

});
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformCustomImport.tsx(2,11): error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformCustomImport.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
const a = <>
~~
!!! error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.
<p></p>
text
<div className="foo"></div>
</>

export {};
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformCustomImport.tsx(2,11): error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformCustomImport.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
const a = <>
~~
!!! error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.
<p></p>
text
<div className="foo"></div>
</>

export {};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
tests/cases/conformance/jsx/jsxs/preact.tsx(3,11): error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/react.tsx (0 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource react */
import "./preact";
const a = <>
<p></p>
text
<div className="foo"></div>
</>

export {};
==== tests/cases/conformance/jsx/jsxs/preact.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource preact */
const a = <>
~~
!!! error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.
<p></p>
text
<div className="foo"></div>
</>

export {};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
tests/cases/conformance/jsx/jsxs/preact.tsx(3,11): error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/react.tsx (0 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource react */
import "./preact";
const a = <>
<p></p>
text
<div className="foo"></div>
</>

export {};
==== tests/cases/conformance/jsx/jsxs/preact.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource preact */
const a = <>
~~
!!! error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.
<p></p>
text
<div className="foo"></div>
</>

export {};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformKeyPropCustomImport.tsx(3,11): error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformKeyPropCustomImport.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
const props = { answer: 42 }
const a = <div key="foo" {...props}>text</div>;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.
const b = <div {...props} key="bar">text</div>;

export {};

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformKeyPropCustomImport.tsx(3,11): error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/jsxJsxsCjsTransformKeyPropCustomImport.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
const props = { answer: 42 }
const a = <div key="foo" {...props}>text</div>;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.
const b = <div {...props} key="bar">text</div>;

export {};

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
tests/cases/conformance/jsx/jsxs/preact.tsx(4,11): error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/react.tsx (0 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource react */
import "./preact";
const props2 = { answer: 42 }
const a2 = <div key="foo" {...props2}>text</div>;
const b2 = <div {...props2} key="bar">text</div>;

export {};

==== tests/cases/conformance/jsx/jsxs/preact.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource preact */
const props = { answer: 42 }
const a = <div key="foo" {...props}>text</div>;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2307: Cannot find module 'preact/jsx-runtime' or its corresponding type declarations.
const b = <div {...props} key="bar">text</div>;

export {};

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
tests/cases/conformance/jsx/jsxs/preact.tsx(4,11): error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.


==== tests/cases/conformance/jsx/jsxs/react.tsx (0 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource react */
import "./preact";
const props2 = { answer: 42 }
const a2 = <div key="foo" {...props2}>text</div>;
const b2 = <div {...props2} key="bar">text</div>;

export {};

==== tests/cases/conformance/jsx/jsxs/preact.tsx (1 errors) ====
/// <reference path="/.lib/react16.d.ts" />
/* @jsxImportSource preact */
const props = { answer: 42 }
const a = <div key="foo" {...props}>text</div>;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2307: Cannot find module 'preact/jsx-dev-runtime' or its corresponding type declarations.
const b = <div {...props} key="bar">text</div>;

export {};

Loading