towxml icon indicating copy to clipboard operation
towxml copied to clipboard

在taro3中搭配vue3和typescript使用towxml并获得类型提示

Open CS-liujf opened this issue 1 year ago • 0 comments

先完成#203所说的步骤,我也是将towxml文件夹置于src/components 路径下,然后在页面中引用。注意该页面的配置文件里要先引用towxml组件

export default definePageConfig({
  navigationBarTitleText: 'towxml页面',
  usingComponents: {
    'to-wxml': '../../components/towxml/towxml',
  }
})

页面的引用方式如下:

<template>
  <view><to-wxml :nodes="article" /></view>
</template>

<script lang="ts" setup>
import towxml from '@/components/towxml';
import { ref } from 'vue';
const article = ref()
article.value = towxml(`# fsdf`, 'markdown')
console.log(article.value)
</script>

<style module></style>

但是,此时引入的towxml函数是没有任何类型提示的,为了增加类型提示我在towxml文件夹内创建index.d.ts

declare module '@/components/towxml' { //注意module的名字一定要和你import ... from那里对应
    export type Option = {
        base?: string
        theme?: 'light' | 'dark'
        events?: {
            [eventName: string]: (e: Event) => any;
        }
    };

    export type WXMLNode = {
        type: string
        attrs: {
            class?: string
            [attrs: string]: string | undefined
        },
        tag: string
        rely: boolean
        children?: WXMLNode[]
    }

    export type HTMLNode = {
        tag: string
        attrs: {
            class?: string
            [attrs: string]: string | undefined
        }
        child: HTMLNode
    }


    export type ParsedResult = {
        theme: 'light' | 'dark'
        children: WXMLNode[]
        _e: {
            child: (HTMLNode | { text: '↵' })[]
        }
    };

    function towxml(str: string, type: 'markdown' | 'html', option?: Option): ParsedResult;
    export default towxml;
}

CS-liujf avatar Aug 10 '23 00:08 CS-liujf