位置:首页 > web前端 > vue

vite.config.ts 怎么配置比较实用 vite.config.ts 常规配置推荐

dearweb 发布:2022-06-29 14:17:14阅读:

最近发现有好多进入v3的小伙伴,不知道 vite.config.ts 怎么配置,本文根据个人经验以及网上的推荐总结出来的配置,希望可以帮到各位。


开启JSX

编写高性能的组件,JSX列子组件

new Vue({
    el: '#demo',
    render: function (h) {
        return (
            <AnchoredHeading level={1}>
                <span>Hello</span> world!
            </AnchoredHeading>
        )
    }
})
import vueJsx from '@vitejs/plugin-vue-jsx'

export {
    vueJsx
}

配置多页面

rollupOptions: {
    input: {
        example: path.resolve(process.cwd(), 'index.html'), // 把页面放在外面,路径简短 防止src/packages/web/index.html ,建议vite把key(web、lib)可也阔以映射成页面路径,就避免这个问题
        lib: path.resolve(process.cwd(), 'lib.html')
    },
}

压缩最小输出

rollupOptions: {
    // 两种方式
    // 一,也可以指定包名打包
    // output: {
    //     manualChunks: {
    //         "vxe-table": ["vxe-table"],
    //         "echarts": ["echarts"],
    //         "xe-utils": ["xe-utils"],
    //         "lodash": ['lodash'],
    //         "ant-design-vue": ['ant-design-vue'],
    //         "@antv/g2plot": ['@antv/g2plot'],
    //         "@antv/g2": ['@antv/g2'],
    //     }
    // },
    // 二,自动分割包名输出 chunkSizeWarningLimit 配置大小
    output: {
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/static/[name]-[hash].[ext]',
        manualChunks(id: any) {
            if (id.includes('node_modules')) {
                return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
        }
    },
},

移除console

terserOptions: {
    compress: {
        drop_console: true,
        drop_debugger: true,
    },
}

配置别名

resolve: {
    alias: {
        // 如果报错__dirname找不到,需要安装node,执行yarn add @types/node --save-dev
        "@": path.resolve(__dirname, "src"),
        "__ROOT__": path.resolve(__dirname, ""),
        "comps": path.resolve(__dirname, "src/components"),
    }
},

当配置了别名的时候,为了让编辑器能更好的识别别名,需要配置jsconfig.json文件,放在vite.config.ts同级别即可,编辑器会自动读取

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "@/*": [
                "src/*"
            ],
            "__ROOT__/*": [
                "*"
            ]
        }
    },
    "exclude": [
        "node_modules"
    ]
}

vxe-table表格,按需加载

一个基于 vue 的 PC 端表格组件,支持增删改查、虚拟列表、虚拟树、懒加载、快捷菜单、数据校验、打印导出、表单渲染、数据分页、弹窗、自定义模板、渲染器、贼灵活的配置项、扩展接口等.

import styleImport from 'vite-plugin-style-import' //按需加载模块

export function configStyleImport() {
    return styleImport({
        libs: [
            {
                libraryName: 'vxe-table',
                esModule: true,
                resolveComponent: (name) => `vxe-table/es/${name}`,
                resolveStyle: (name) => `vxe-table/es/${name}/style.css`
            }
        ]
    })
}

开启压缩

import viteCompression from 'vite-plugin-compression' // 开启压缩

export function configViteCompression() {
    // 开启压缩 [文档](https://github.com/anncwb/vite-plugin-compression/blob/main/README.zh_CN.md)
    return  viteCompression({
        verbose: true,
        disable: false,
        // filter:()=>{}, // 那些资源不压缩
        threshold: 1024 * 50, // 体积大于 threshold 才会被压缩,单位 b
        deleteOriginFile: false,// 压缩后是否删除源文件
        algorithm: 'gzip', // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        ext: '.gz', // 生成的压缩包后缀
    })
}

开启CDN

字只需要配置即可,自动生成模板所引用的cdn路径

import importToCDN from 'vite-plugin-cdn-import'

export function configCDN() {
    return importToCDN({
        modules: [
            {
                name: 'element-plus',
                var: 'ElementPlus',
                path: 'https://unpkg.com/element-plus/lib/index.full.js',
                css: 'https://unpkg.com/element-plus/lib/theme-chalk/index.css',
            },
            {
                name: 'vant',
                var: 'vant',
                path: 'https://cdn.jsdelivr.net/npm/vant@next/lib/vant.min.js',
                css: 'https://cdn.jsdelivr.net/npm/vant@next/lib/index.css',
            }
        ]
    })
}

注入变量到html模板中

import html from 'vite-plugin-html'

export function configHtml(opt: any) {
    return html({
        inject: {
            injectData: {...opt.variables}
        },
        minify: true
    })
}

配置构建依赖包lib

lib: {
    entry: path.resolve(process.cwd(), 'src/packages/install.ts'),
    name: 'vueViteAdminTs', // 构建依赖包的时候, 对外暴露的名称
    fileName: (format: string) => `index.${format}.js`,
    rollupOptions: {
        external: ['vue', 'vue-router'],
        output: {
            globals: {
                vue: 'Vue'
            }
        }
    }
},
rollupOptions: {
    output: {
        inlineDynamicImports: true,
    }
}

配置代理

export function configServer() {
    return {
        host: '0.0.0.0',
        port: 8290,
        https: false,
        proxy: {
            '^/api': {
                target: 'http://127.0.0.1:7001',
                changeOrigin: true,
                rewrite: (path: any) => path.replace(/^/api/, '')
            }
        }
    }
}

配置less

修改全局less变量

import theme from '../../src/packages/theme/ming'

export function configCss() {
    return {
        preprocessorOptions: {
            less: {
                modifyVars: {
                    ...theme
                },
                javascriptEnabled: true,
            },
        }
    }
}

推荐配置

windicss
import WindiCSS from 'vite-plugin-windicss'

export default {
  plugins: [
    WindiCSS(),
  ],
}

如果担心命名冲突,在根目录新建windi.config.ts,可以通过以下方式给属性模式添加自定义前缀:

export default {
  attributify: {
    prefix: 'w:',
  },
}

使用列子:

<button
  w:bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600"
  w:text="sm white"
  w:font="mono light"
  w:p="y-2 x-4"
  w:border="2 rounded blue-200"
>
  Button
</button>
vite-svg-loader
vite-svg-loader插件可以让你像引用组件一样引用svg文件.

import svgLoader from 'vite-svg-loader'
export default defineConfig({ plugins: [vue(), svgLoader()] })
使用

<template>
  <MyIcon />
</template>

<script setup>
import MyIcon from './my-icon.svg'
</script>
vite-plugin-components
vite-plugin-components可以实现组件库或内部组件的自动按需引入组件,而不需要手动的进行import,可以帮我们省去不少import的代码

import Vue from '@vitejs/plugin-vue'
import ViteComponents from 'vite-plugin-components'

export default {
  plugins: [
    Vue(),
    ViteComponents()
  ],
};

好了,关与vite的配置,我就先写到这了,至于后面有新的配置,或者有新的变化,我会在这个仓库里面进行配置,以及验证可行性


24人点赞 返回栏目 提问 分享一波

小礼物走一波,支持作者

还没有人赞赏,支持一波吧

留言(问题紧急可添加微信 xxl18963067593) 评论仅代表网友个人 留言列表

暂无留言,快来抢沙发吧!

本刊热文
网友在读
手机扫码查看 手机扫码查看