unplugin-vue-components调研

778 阅读1分钟

github地址:unplugin-vue-components

// vite.config.ts
import Components from 'unplugin-vue-components/vite'

// ElementPlusResolver, AntDesignVueResolver, VantResolver
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    Components({
      // relative paths to the directory to search for components.
      dirs: ['src/components'],

      // valid file extensions for components.
      extensions: ['vue'],
      // search for subdirectories
      deep: true,
      // resolvers for custom components
      resolvers: [
        ElementPlusResolver()
      ],

      // generate `components.d.ts` global declarations,
      // also accepts a path for custom filename
      // default: `true` if package typescript is installed
      dts: true,

      // Allow subdirectories as namespace prefix for components.
      directoryAsNamespace: false,
      // Subdirectory paths for ignoring namespace prefixes
      // works when `directoryAsNamespace: true`
      globalNamespaces: [],

      // auto import for directives
      // default: `true` for Vue 3, `false` for Vue 2
      // Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
      // To install Babel, run: `npm install -D @babel/parser`
      directives: true,

      // Transform path before resolving
      importPathTransform: v => v,

      // Allow for components to override other components with the same name
      allowOverrides: false,

      // filters for transforming targets
      include: [/\.vue$/, /\.vue\?vue/],
      exclude: [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/],

      // Vue version of project. It will detect automatically if not specified.
      // Acceptable value: 2 | 2.7 | 3
      version: 3
    }),
  ],
})
  • 上面配置其中dirs默认是src/components,且优先级高于exclude,因此如果你想忽略自定义组件目录src/components,你需要改写其他路径

  • 配置完成启动项目后,插件会扫描业务源代码,在项目根目录下自动生成components.d.ts文件(dts设置为true),同时需要在tsconfig.json文件include项加上该文件路径

  • 【缺点】:由于代码中缺少组件引入,vscode插件Volar目前无法自动识别组件,这是目前最大的问题
  • 友情插件:unplugin-auto-import 框架成员自动导入插件,无须手动导入