vue3+vite的按需引入神器:unplugin-vue-components/vite

前言:

        vue3项目中,vite提供了按需引入的插件:unplugin-vue-components/vite ,使用他以后,我们再也不用挨个引入组件了,相当方便。

使用步骤:

1、安装 npm/cnpm/pnpm/yarn  都可以,装上下面两个插件

unplugin-vue-components/vite 

2、vite.config.js中配置

import Components from 'unplugin-vue-components/vite'; // 按需加载自定义组件

//下面根据你的项目实际需要
import {join} from 'node:path';
const PROJECT_ROOT = '../..';

const config = {
    plugins: [
        Components({
          dts: true,
          dirs: [join(PACKAGE_ROOT, 'src') + '/components'], // 按需加载的文件夹
            //dirs:'src/components'
          resolvers: [], // ElementPlus按需加载
        }),
    ]
    
}

3、配置完成后,运行代码,会在项目根目录自动生成一个components.d.ts文件。

4、tsconfig.json的配置

{
  "compilerOptions": {
    "module": "esnext",
    "resolveJsonModule": true,
    "target": "esnext",
    "allowSyntheticDefaultImports": true,
    "sourceMap": false,
    "moduleResolution": "Node",
    "skipLibCheck": true,
    "strict": false,
    "isolatedModules": true,
    "jsx": "preserve",
    "types":  ["vite-plugin-pages/client",  "vite/client", "vite-plugin-vue-layouts/client", "node"],

    "baseUrl": ".",
    "paths": {
      "#preload": ["../preload/src/index"],
      "/@/*": ["./src/*"]
    },
    "lib": ["ESNext", "dom", "dom.iterable"]
  },
  "include": [
    "src/**/*.vue",
    "src/**/*.ts",
    "src/**/*.tsx",
    "types/**/*.d.ts",
    "src/**/*.json",
    "src/*json",

    "../../types/**/*.d.ts"
  ],
  "exclude": ["**/*.spec.ts", "**/*.test.ts"]
}

5、新建一个组件 ,可以看到 components.d.ts中已经自动加入了我们的组件

 6、页面上使用

<textBlueBg
     class="me-2"
     :text="nowLang === 'zh'?item.nick_name:item.cn_nick_name"
/>

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/131855469
今日推荐