Skip to content
On this page

vite 开发中常用的插件

一、支持tsx语法 @vitejs/plugin-vue-jsx

插件地址: https://www.npmjs.com/package/@vitejs/plugin-vue-jsx

ts
// vite.config.js
import vueJsx from '@vitejs/plugin-vue-jsx'

export default {
    plugins: [
        vueJsx({
            // options are passed on to @vue/babel-plugin-jsx
        })
    ]
}

二、按需加载 unplugin-vue-components

1、安装依赖

ts
pnpm add unplugin-vue-components -D

2、vite.config中的配置

ts
// 以ant-design-vue 组件为例
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'

Components({
    dts: true,
    dirs: [],
    resolvers: [
        AntDesignVueResolver({
            importStyle: 'less',
            importLess: true,
            resolveIcons: false
        }),

        (name) => {
            const components = [
                {
                    name: 'DtTheme',
                    styleDir: 'theme'
                }
            ]

            const comp = components.filter( it => it.name === name )
            if(comp.length > 0) {
                return {
                    // 组件名称
                    name,
                    // 组件来源
                    from: '@dt-frames/ui',
                    // 自动引入的css路径
                    sideEffects: `/node_modules/@dt-frames/ui/es/${ comp[0].styleDir }/index.less`
                }
            }
        }
    ]
}),

3、tsconfig.json配置

如果不配置ts提示,悬浮在组件上会提示'unknown'

ts
{
    include: [
		xxx
		"./components.d.ts"
        xxx
    ]
}

三、自动生成别名 vite-aliases

插件地址: https://npmmirror.com/package/vite-aliases

ts
// 下载依赖包
pnpm add vite-aliases -D


// vite.config.js
import { ViteAliases } from 'vite-aliases'

export default {
	plugins: [
		ViteAliases()
	]
};

四、自动生成路由 vite-plugin-pages

插件地址: https://www.npmjs.com/package/vite-plugin-pages

安装依赖

ts
pnpm add vite-plugin-pages -D

配置插件

ts
// vite.config.js
import Pages from "vite-plugin-pages"

export default {
    plugins: [
        Pages({
            // 需要生成路由的文件目录,默认就是识别src下面的views文件
            dirs: "src/views",
            // 后缀名为'vue' | 'tsx'的文件自动生成路由
            extensions: ['vue', 'tsx'],
            // 排除在外的目录,即不将所有 components 目录下的 .vue 文件生成路由
            exclude: ["**/components/*", '**/shared/*', '**/*.component.*', "src/**/src/**"], 
            // 路由重构
            onRoutesGenerated: (routes) => {
                routes.forEach((route) => {
                    if (route.path.startsWith('/')) {
                        route.path = route.path.slice(1)
                    }
                })
            }
        }),
    ],
}

挂载路由

配置-router/index.js配置,main.js中正常挂载路由

ts
import { createApp } from 'vue'
import { createRouter, createWebHistory } from "vue-router"
import routes from "~pages"
import App from './App.vue'

const router = createRouter({
    history: createWebHistory(),
    routes,
})

createApp(App).use(router).mount('#app')

五、压缩代码 vite-plugin-compression

插件使用: https://blog.csdn.net/Old_Soldier/article/details/127192862

ts
// 安装
pnpm add vite-plugin-compression -D


// vite.config.ts
import compressPlugin from 'vite-plugin-compression'

export default {
    plugins: [
        compressPlugin({
            ext: '.gz',
            algorithm: 'gzip',
            deleteOriginFile:true
        })
    ]
}

六、自动导入 unplugin-auto-import/vite

插件地址: https://www.npmjs.com/package/unplugin-auto-import

ts
// 安装
pnpm add unplugin-auto-import -D

// plugin use
AutoImport({
    // targets to transform
    include: [
        /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
        /\.vue$/, /\.vue\?vue/, // .vue
        /\.md$/, // .md
    ],

    // global imports to register
    imports: [
        // presets
        'vue',
        'vue-router',
        // custom
        {
        '@vueuse/core': [
            // named imports
            'useMouse', // import { useMouse } from '@vueuse/core',
            // alias
            ['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
        ],
        'axios': [
            // default imports
            ['default', 'axios'], // import { default as axios } from 'axios',
        ],
        '[package-name]': [
            '[import-names]',
            // alias
            ['[from]', '[alias]'],
        ],
        },
    ],

    // Auto import for module exports under directories
    // by default it only scan one level of modules under the directory
    dirs: [
        // './hooks',
        // './composables' // only root modules
        // './composables/**', // all nested modules
        // ...
    ],

    // Filepath to generate corresponding .d.ts file.
    // Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
    // Set `false` to disable.
    dts: './auto-imports.d.ts',

    // Auto import inside Vue template
    // see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
    vueTemplate: false,

    // Custom resolvers, compatible with `unplugin-vue-components`
    // see https://github.com/antfu/unplugin-auto-import/pull/23/
    resolvers: [
        /* ... */
    ],

    // Generate corresponding .eslintrc-auto-import.json file.
    // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
    eslintrc: {
        enabled: false, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
    },
})

七、低版本兼容 @vitejs/plugin-legacy

插件地址: https://www.npmjs.com/package/@vitejs/plugin-legacy

ts
// 安装
pnpm add @vitejs/plugin-legacy terser -D

// vite.config.js
import legacy from '@vitejs/plugin-legacy'

export default {
    plugins: [
        legacy({
            targets: ['ie >= 11'],
            additionalLegacyPolyfills: ['regenerator-runtime/runtime']
        })
    ]
}