Vue3+vite优化基础架构(1)--- 使用unplugin-vue-components

发布于:2024-04-28 ⋅ 阅读:(18) ⋅ 点赞:(0)

Vue3+vite优化基础架构(1)--- 使用unplugin-vue-components

说明

这里记录下自己在Vue3+vite的项目使用unplugin-vue-components/vite来自定义组件自动全局引入svg雪碧图组件,不使用ts语法,方便以后直接使用。这里承接自己的博客Vue3+vite搭建基础架构(11)— 菜单栏功能和Tab页功能实现这篇博客,在该博客项目的基础上增加使用unplugin-vue-components/vite来使组件全局引用。

unplugin-vue-components官网https://github.com/antfu/unplugin-vue-components#readme

安装unplugin-vue-components

命令如下,-D表示该依赖添加在package.json里面的devDependencies。

devDependencies下的依赖包,只是我们在本地或开发坏境下运行代码所依赖的,若发到线上,其实就不需要devDependencies下的所有依赖包;(比如各种loader,babel全家桶及各种webpack的插件等)只用于开发环境,不用于生产环境,因此不需要打包。

npm install unplugin-vue-components -D

在webstorm里面的Terminal输入npm install unplugin-vue-components -D命令安装该依赖。执行完如下:
在这里插入图片描述
package.json会增加unplugin-vue-components版本号
在这里插入图片描述

vite.config.js中使用unplugin-vue-components/vite

官网提供的配置属性如下:

Components({
  // relative paths to the directory to search for components.
  dirs: ['src/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/components/*.{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: 2.7,

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

在vite.config.js添加如下代码:
在这里插入图片描述
代码如下:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
//引入path用于写别名配置,自带无须安装
import path from 'path'
//使用svg-icons插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
//使用vite-plugin-vue-setup-extend
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
//使用unplugin-vue-components/vite按需加载自定义组件
import Components from 'unplugin-vue-components/vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // 注册所有的svg文件生成svg雪碧图
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), "src/assets/icons")], //svg图片存放的目录
      symbolId: "icon-[name]", // symbol的id
      inject: "body-last", // 插入的位置
      customDomId: "__svg__icons__dom__" // svg的id
    }),
    VueSetupExtend(),
    // 全部属性如下,这里只使用部分需要的
    Components({
      dirs: ['src/components'], // 指定组件位置,默认指定文件夹是src/components
      extensions: ['vue'], // 组件的有效文件扩展名
      deep: true, // 搜索子目录
      dts: 'src/components/components.d.ts', //配置文件生成位置,默认情况下启用,如果为true,表示默认生成到根目录文件下,false为不生成该文件,这里我没有安装ts,生成ts文件发现并没有报错,测试打包发现也没有报错
      //resolvers: [], // 自定义组件的解析器,可以将ElementPlus组件改为到这个里面使用
      //directoryAsNamespace: false, // 允许子目录作为组件的命名空间前缀
      //globalNamespaces: [], // 忽略命名空间前缀的子目录路径,当directoryAsNamespace: true 时有效
      //directives: true, //需要 Babel 来为 Vue 2 进行转换,出于性能考虑,它默认处于禁用状态。
      //include: [/.vue$/, /.vue?vue/],
      //exclude: [/[\/]node_modules[\/]/, /[\/].git[\/]/, /[\/].nuxt[\/]/],
    })
  ],
  resolve: {
    //别名配置
    alias: {
      '~': path.resolve(__dirname, './'),
      '@': path.resolve(__dirname, 'src')
    },
    //引入文件的时候,可以忽略掉以下文件后缀
    extensions: ['.js', '.mjs', '.vue', '.json', '.less', '.css']
  },
  css:{
    //预处理器配置项
    preprocessorOptions:{
      less:{
        //支持直接使用表达式 width: 100px - 20px;得到值为width:80px;
        math: "always"
      }
    }
  }
})

启动项目后才会生成components.d.ts,文件位置如下:
在这里插入图片描述
删除掉之前项目中以下代码和文件,使用unplugin-vue-components/vite来代替全局组件的使用。
在这里插入图片描述
浏览器结果如下,图标正常显示出来,与之前一模一样:
在这里插入图片描述

到这里使用unplugin-vue-components/vite来使svg-icon组件进行全局引用的目的就达成了,后面如果还需要添加其他组件,直接在/src/components下添加相应组件文件即可。它会自动添加到components.d.ts文件里面。
注意:如果你把项目中/src/components下的svg-icon的组件文件夹给删除了,components.d.ts里面并不会自动删除SvgIcon: typeof import(‘./svg-icon/index.vue’)[‘default’]这句代码,需要自己手动进行删除。


网站公告

今日签到

点亮在社区的每一天
去签到