[英]Using JSX in TypeScript without React
What is a simple way to have TypeScript recognize JSX (especially in VS Code) without having React as a dependency?什么是让 TypeScript 识别 JSX(尤其是在 VS Code 中)而不将 React 作为依赖项的简单方法? If we have to use a custom JSX namespace and a custom renderer, then what is the expected shape of the contents of that namespace and the renderer?
如果我们必须使用自定义 JSX 命名空间和自定义渲染器,那么该命名空间和渲染器的内容的预期形状是什么?
As far as I know, JSX is just syntactic sugar that is transformed into function calls (eg, React.createElement
), so there should be a way to specify that a different function should be used for transforming the JSX.据我所知,JSX 只是转换为函数调用的语法糖(例如
React.createElement
),所以应该有一种方法来指定应该使用不同的函数来转换 JSX。
Looking at the release docs for TypeScript 2.8 , I see there are sections titled "Per-file JSX factories" and "Locally scoped JSX namespaces" , but I don't see these sections in the official current TypeScript docs. 查看 TypeScript 2.8的发布文档,我看到有标题为"Per-file JSX factory"和"Locally scoped JSX namespaces" 的部分,但我在当前的官方 TypeScript 文档中没有看到这些部分。 Have these features been deprecated?
这些功能是否已被弃用?
jsx
and jsxFactory
compiler options are responsible for that. jsx
和jsxFactory
编译器选项对此负责。
TypeScript expects a function defined in jsxFactory
to exist in module scope. TypeScript 期望
jsxFactory
定义的函数存在于模块范围内。 Usually this requires to import React
because jsxFactory
defaults to React.createElement
.通常这需要导入
React
因为jsxFactory
默认为React.createElement
。
If the compiler is configured with:如果编译器配置为:
...
"jsx": "react",
"jsxFactory": "h",
...
Then h
function should exist.那么
h
函数应该存在。 JSX-related types should be defined to make type checks work properly:应该定义 JSX 相关类型以使类型检查正常工作:
declare namespace JSX {
interface Element {}
interface ElementClass {
render(): any;
}
interface IntrinsicElements {
div: any;
// ...
}
}
const h = (Comp: any): any => console.log(`creating ${Comp} element`);
<div/>;
class FooComponent {
render = () => null;
}
<FooComponent/>;
The Typescript compiler has flags that allow you to specify how TSX/JSX is handled. Typescript 编译器具有允许您指定如何处理 TSX/JSX 的标志。
Specifically, you have to specify "--jsx=React" and "--jsxFactory=someModule.yourJsxFactory", and in your tsx files, you supply your custom factory by importing "someModule", from which "yourJsxFactory" should be exported.具体来说,您必须指定“--jsx=React”和“--jsxFactory=someModule.yourJsxFactory”,并且在您的 tsx 文件中,您通过导入“someModule”来提供您的自定义工厂,“yourJsxFactory”应该从中导出。
Read more about it at阅读更多关于它的信息
Typescript (Compiler Options) 打字稿(编译器选项)
and和
Typescript (JSX)打字稿 (JSX)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.