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

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的插件等)只用于开发环境,不用于生产环境,因此不需要打包。

javascript 复制代码
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

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

javascript 复制代码
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添加如下代码:

代码如下:

javascript 复制代码
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']这句代码,需要自己手动进行删除。

相关推荐
天下无贼!43 分钟前
2024年最新版Vue3学习笔记
前端·vue.js·笔记·学习·vue
Jiaberrr44 分钟前
JS实现树形结构数据中特定节点及其子节点显示属性设置的技巧(可用于树形节点过滤筛选)
前端·javascript·tree·树形·过滤筛选
赵啸林1 小时前
npm发布插件超级简单版
前端·npm·node.js
我码玄黄1 小时前
THREE.js:网页上的3D世界构建者
开发语言·javascript·3d
罔闻_spider1 小时前
爬虫----webpack
前端·爬虫·webpack
吱吱鼠叔1 小时前
MATLAB数据文件读写:1.格式化读写文件
前端·数据库·matlab
爱喝水的小鼠2 小时前
Vue3(一) Vite创建Vue3工程,选项式API与组合式API;setup的使用;Vue中的响应式ref,reactive
前端·javascript·vue.js
小晗同学2 小时前
Vue 实现高级穿梭框 Transfer 封装
javascript·vue.js·elementui
盏灯2 小时前
前端开发,场景题:讲一下如何实现 ✍电子签名、🎨你画我猜?
前端
WeiShuai2 小时前
vue-cli3使用DllPlugin优化webpack打包性能
前端·javascript