Skip to content

TypeScript 示例

本页面展示了如何在 VitePress 中使用 TypeScript 和 Vue 组件。

基本用法

下面是一个使用 TypeScript 的 Vue 组件示例:

TypeScript 组件

这是一个使用 TypeScript 的 Vue 组件 (计数: 0)

0

自定义属性

您可以自定义组件的属性:

自定义标题

这是一个自定义消息 (计数: 0)

0

在 Markdown 中使用 TypeScript

您也可以在 Markdown 文件中直接使用 TypeScript 代码块:

ts
// 定义接口
interface User {
  id: number;
  name: string;
  email: string;
  isActive: boolean;
}

// 创建用户函数
function createUser(name: string, email: string): User {
  return {
    id: Math.floor(Math.random() * 1000),
    name,
    email,
    isActive: true,
  };
}

// 使用函数
const user = createUser("张三", "zhangsan@example.com");
console.log(user);

在 VitePress 中使用 TypeScript

在 VitePress 项目中使用 TypeScript 的主要步骤:

  1. 安装必要的依赖:

    bash
    pnpm add -D typescript vue @types/node
  2. 创建 tsconfig.json 文件:

    json
    {
      "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "moduleResolution": "node",
        "strict": true,
        "jsx": "preserve"
        // 其他配置...
      }
    }
  3. 创建 Vue 组件类型声明文件:

    ts
    // .vitepress/types/vue-shim.d.ts
    declare module "*.vue" {
      import type { DefineComponent } from "vue";
      const component: DefineComponent<{}, {}, any>;
      export default component;
    }
  4. .vitepress/theme/index.ts 中使用 TypeScript:

    ts
    import type { Theme } from "vitepress";
    import DefaultTheme from "vitepress/theme";
    
    export default {
      // 配置...
    } satisfies Theme;

下一步

基于 MIT 许可发布