You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不转TypeScript的情况下为Vue3 JSX组件库生成.d.ts声明文件?

为Vue3 JSX组件库生成TypeScript声明文件(保留JS/JSX格式)

1. 为单个组件编写精准的类型声明

针对每个JSX组件,创建同名的.d.ts文件来定义props类型和组件类型,以你的Button.jsx为例:

在src/Button.d.ts中写入:

import type { DefineComponent } from 'vue';

// 定义Button组件的props类型
export interface ButtonProps {
  text?: string; // 根据需求设置可选/必填属性
}

// 声明Button组件为Vue的定义组件类型
declare const Button: DefineComponent<ButtonProps>;

export default Button;

这样IDE就能识别text prop的类型,提供补全和校验支持。

2. 统一导出所有组件的类型

修改根目录的index.d.ts,导入各组件的类型后统一导出:

import Button from './src/Button';
import Tabs from './src/Tabs';
import Select from './src/Select';

export { Button, Tabs, Select };
export default { Button, Tabs, Select };

确保每个组件都有对应的.d.ts文件,和组件文件放在同一目录下。

3. 配置项目文件确保类型生效

  • 在package.json中保持typings字段指向根目录的声明文件:
    {
      "typings": "./index.d.ts",
      "files": [
        "src",
        "index.d.ts"
      ]
    }
    
  • 若需要自动生成基础声明文件,可配置tsconfig.json:
    {
      "compilerOptions": {
        "declaration": true,
        "emitDeclarationOnly": true,
        "allowJs": true,
        "jsx": "preserve",
        "moduleResolution": "node"
      },
      "include": ["src/**/*.jsx"]
    }
    
    执行命令生成基础声明:
    npx @vue/tsc --declaration --emitDeclarationOnly --allowJs
    
    自动生成的声明可能不够精准(比如从数组props无法推断具体类型),需要手动调整成接口形式。

注意事项

  • 手动编写的类型声明优先级高于自动生成的,若自动生成的不符合需求,直接修改对应的.d.ts文件即可。
  • 确保项目已安装Vue的类型依赖,TypeScript能识别Vue的内置类型。

内容的提问来源于stack exchange,提问作者SavvyShah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:02:17