美文网首页
vite的auto import

vite的auto import

作者: Lisa_Guo | 来源:发表于2023-04-12 18:28 被阅读0次

解决开发中经常使用的ref, computed等需要频繁引入的问题

1. 插件

unplugin-auto-import:auto import api for vite,webpack,rollup and esbuild。官网

// import { computed, ref } from 'vue'  不再需要
const count = ref(0)
const doubled = computed(() => count.value * 2)

unplugin-vue-components: auto import for vue,支持按需引入各类vue的组件库、自定义组件 官网

<template>
  <div>
   <!-- 组件可直接使用 -->
   <a-input v-model:value="name" />
    <HelloWorld msg="Hello Vue 3.0 + Vite" />
  </div>
</template>

<script>
const name = ref('')  // ref可直接使用
</script>

2. 自动引入组件库

如ant design vue,使用时无需import

// vite.config.ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  // ...
  plugins: [
    // ...
    AutoImport({
      resolvers: [AntDesignVueResolver()], // api
    }),
    Components({
      resolvers: [AntDesignVueResolver()], // 组件
    }),
  ],
})

3. 自动导入components下的组件

// vite.config.js
 Components({
        // 指定组件所在位置,默认为 src/components。可省略
        // 使用自己定义组件的时候免去 import 的麻烦
        // path可以使用通配符,'!' 表示排除条件
        dirs: ['src/components/**/index.vue', 'src/pages/**/!(index.vue)/'],
        // 配置需要将哪些后缀类型的文件进行自动按需引入,'vue'为默认值。可省略
        extensions: ['vue'],
        // 解析组件,这里以 AntDesignVue 为例,不同的组件需要不同的resolver
        resolvers: [AntDesignVueResolver()],
        // 生成components.d.ts, 可省略
        // components.d.ts是代码中用到的组件的声明文件,默认在根目录,也可指定文件路径。 默认为true,可省略。
        dts: true,  // boolean | string
        // 遍历子目录。可省略
        deep: true
      }),

dts:true 或者为 'src/components.d.ts'时,则会自动生成components.d.ts文件
components.d.ts:**.d.ts为全局声明文件,包含了按需导入的组件的声明。内容:

/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'

export {}

declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    // ant-design-vue的组件
    AButton: typeof import('ant-design-vue/es')['Button']
    ASelect: typeof import('ant-design-vue/es')['Select']
    ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
    // vue-router的组件
    RouterLink: typeof import('vue-router')['RouterLink']
    RouterView: typeof import('vue-router')['RouterView']
    // components目录下的自定义组件
    Svgicon: typeof import('./src/components/svgicon/index.vue')['default']
  }
}

4 自动导入api

AutoImport可自动导入指定的api

AutoImport({
   // 自动导入vue相关的Api
   imports: [
       'vue',   // 导入内置的所有api
       'vue-router',
       'pinia',
       '@vueuse/core',
       {
            'vue-router': ['createRouter'],     // 导入指定的api
            /* 自定义模块 */
            '@/hooks/api.ts': ['defineApi'],    // 导入指定文件下的指定api
            '@/api/index.ts': [['*', 'api']],        // 导入指定文件下的api,并重命名
            '@/store/index.ts': [['*', 'store']], 
       }
     ],
     include: [/\.[tj]sx?$/, /\.vue$/], // 匹配的文件,也就是哪些后缀的文件需要自动引入
     // 生成auto-import.d.ts声明文件
     dts: 'src/auto-import.d.ts',
     resolvers: [AntDesignVueResolver()]
   }),

做了以上声明后,使用时无需手动引入

<script setup lang="ts">
// 可直接使用
const userApi = api.user
const userStore = store.user
const name = ref()
</script>

auto-imports.d.ts列出按需自动导入的api的声明

export {}
declare global {
  const EffectScope: typeof import('vue')['EffectScope']
  const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
  const api: typeof import('@/api/index')
  const computed: typeof import('vue')['computed']
  const createApp: typeof import('vue')['createApp']
  const createPinia: typeof import('pinia')['createPinia']
  const customRef: typeof import('vue')['customRef']
  ...
}
// for type re-export
declare global {
  // @ts-ignore
  export type { Component, ComponentPublicInstance, ComputedRef, InjectionKey, PropType, Ref, VNode } from 'vue'
}

5 校验

如果出现undef的提示,可尝试

  • 确保’auto-import.d.ts‘ 在tsconfig.json的include之内
  • eslint里配置
// vite.config.js
AutoImport({
    eslintrc: {
      enabled: false, // 若没此json文件,先开启,生成后在关闭
      filepath: './.eslintrc-auto-import.json', // 设置eslintrc-auto-import.json生成路径 Default `./.eslintrc-auto-import.json`
      globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
   })
// .eslintrc.js
extends: [ ...
  ./.eslintrc-auto-import.json
]
  • 在d.ts中定义的声明,在ts文件正常,但.vue中提示未定义
    在.eslintrc.js中禁用 no-undef: 'off', ts已经做了undef的校验,不再需要eslint
  • vue的template中自动导入的api无法识别
    需要在ts代码中引入
<template>
  {{ store.user.name }}  // 报错 store == undefined
 {{ userStore.name }}  // 需在ts里调用
</template>
<script setup lang="ts">
const userStore = store.user
</script>

相关文章

网友评论

      本文标题:vite的auto import

      本文链接:https://www.haomeiwen.com/subject/uujoddtx.html