vue自动导入组件和自动导入类库 api

2023-05-26 15:45:26 浏览数 (1)

vue3 项目中,使用 vue 常用的 api 比如 vuex 的 api 或者 ref,reactive 等,以及导入多个自定义组件、UI 组件库的组件,都需要反复的手动导入,注册,很是影响开发体验,这里推荐 antfu 开源的两个插件,上链接:

自动导入组件

https://github.com/antfu/unplugin-vue-components

自动导入类库 api 

https://github.com/antfu/unplugin-auto-import

支持 vue-cli、vite、webpack、rollup 等配置,建议大家直接看文档,先配置默认配置,之后修改部分即可。

建议将配置文件单独提取出来,方便维护。

踩坑注意:

自动导入组件的配置:

globs 是全局注册要自动导入的 vue 组件目录,(优先级高于 dirs 和 extensions)但是写了没有生效,于是 我改为 使用 dirs,可以生效。

代码语言:javascript复制
module.exports = {
  // relative paths to the directory to search for components.
  dirs: ['src/components', 'src/pages/**/components'],

  // valid file extensions for components.
  extensions: ['vue'],

  // Glob patterns to match file names to be detected as components.
  // When specified, the `dirs` and `extensions` options will be ignored.
  // globs: ['src/pages/**/components/*.{vue}', 'src/pages/*/components/*.{vue}', 'src/components/*.{vue}', 'src/components/base/*.{vue}'],

  // search for subdirectories
  deep: true,

  // resolvers for custom components
  resolvers: [],

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

  // Allow subdirectories as namespace prefix for components.
  directoryAsNamespace: false,

  // Collapse same prefixes (camel-sensitive) of folders and components
  // to prevent duplication inside namespaced component name.
  // works when `directoryAsNamespace: true`
  collapseSamePrefixes: 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,

  // Only provide types of components in library (registered globally)
  types: []
}

0 人点赞