Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
CS-liujf opened this issue Aug 10, 2023 · 0 comments
Open

Comments

@CS-liujf
Copy link

CS-liujf commented Aug 10, 2023

先完成 #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 | { type: 'text', attrs: {}, text: '↵', rely: boolean })[]
        _e: {
            child: (HTMLNode | { text: '↵' })[]
        }
    };

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

至此,页面引用该js包时可以引入类型,且towxml函数有相应的类型注释

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

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

<style module></style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant