TypeScript 中的 jsxImportSource

说明 jsxImportSource 如何指定 automatic JSX runtime 的导入来源,以及它为什么常见于 Preact 等非 React 默认 runtime。

#tech / dev #resource / typescript #type / concept #status / growing

[!info] related notes

TypeScript 中的 jsxImportSource

一句话定义

jsxImportSource 用来指定 automatic JSX runtime 该从哪个模块导入 jsx / jsxs 工厂函数。

核心机制 / 工作原理

官方文档明确说明,它作用于:

  • jsx"react-jsx""react-jsxdev" 的场景

这时 TypeScript 会自动插入像:

  • react/jsx-runtime

这样的 runtime 导入。

如果配置:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "preact",
    "types": ["preact"]
  }
}

那么 TypeScript 就会改成从:

  • preact/jsx-runtime

这一侧去拿 runtime 工厂。

最小例子 / 最小场景

切到 Preact runtime

这是它最典型的用途:

  • JSX 语法继续写
  • automatic runtime 的来源不再是 React,而是 Preact 等兼容实现

边界与易混淆点

它不等于 jsx

jsx 更像:

  • 选择 classic / preserve / automatic runtime 模式

jsxImportSource 更像:

  • 在 automatic runtime 模式下,具体从哪个包导入运行时

它常和 types 一起出现

官方文档示例里也把:

  • "types": ["preact"]

一起配上了,因为不仅 runtime 来源变了,编辑器和类型环境也要一起对齐。

per-file pragma 也能覆盖

官方文档还提供了:

/** @jsxImportSource preact */

这种逐文件配置方式。

不过要让它按预期工作,官方文档也特别提醒:

  • 这个 tsx 文件必须包含 importexport
  • 这样它才会被视为 module

参考信息

创建于 2026/5/15 更新于 2026/5/27