defineTemplateConfig

defineTemplateConfig 是用于定义模板配置的函数,提供 TypeScript 类型推导支持。

导入

import { defineTemplateConfig } from 'template-sdk/config'

类型签名

function defineTemplateConfig<T extends TemplateConfig>(
  config: T
): T

参数

参数名 说明 类型 必填
config 模板配置对象 TemplateConfig

返回值

返回配置对象的字面量类型,用于 TypeScript 类型推导。

为什么使用它

使用 defineTemplateConfig 而不是直接导出对象,主要有以下优势:

  • 类型推导:编辑器可以准确知道配置的结构
  • 智能提示:提供更好的代码补全
  • 类型安全:在定义阶段捕获类型错误

使用示例

基础用法

import { defineTemplateConfig } from 'template-sdk/config'

const configJson = defineTemplateConfig({
  meta: {
    name: '示例模板',
    code: 'demo-template'
  },
  dataSchema: {
    fields: [
      { key: 'title', type: 'string', value: '默认标题' }
    ]
  }
})

export default configJson

完整配置示例

import { defineTemplateConfig } from 'template-sdk/config'

const configJson = defineTemplateConfig({
  meta: {
    name: '完整示例模板',
    code: 'full-demo',
    version: '1.0.0'
  },
  dataSchema: {
    fields: [
      // 字符串字段
      {
        key: 'title',
        type: 'string',
        label: '标题',
        value: '欢迎使用'
      },

      // 数字字段
      {
        key: 'count',
        type: 'number',
        label: '数量',
        value: 10
      },

      // 布尔字段
      {
        key: 'showBanner',
        type: 'boolean',
        label: '显示横幅',
        value: true
      },

      // 图片字段
      {
        key: 'poster',
        type: 'image',
        label: '海报',
        value: '/assets/poster.png'
      },

      // 视频字段
      {
        key: 'trailer',
        type: 'video',
        label: '宣传视频',
        value: '/assets/trailer.mp4'
      },

      // 数组字段
      {
        key: 'features',
        type: 'array',
        label: '功能列表',
        operations: ['add', 'delete'],
        value: [
          { key: 'f1', type: 'string', value: '功能一' },
          { key: 'f2', type: 'string', value: '功能二' }
        ]
      }
    ]
  },
  functions: {}
})

export default configJson

在 vite.config 中使用

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import configJson from './src/template/config'
import { templateSdkPlugin } from 'template-sdk/vite'

export default defineConfig({
  plugins: [
    templateSdkPlugin({ configJson }),
    vue()
  ]
})