V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
vipbic
V2EX  ›  分享创造

一份关于 vite.config.ts 项目常用项配置

  •  
  •   vipbic · 2021-12-30 08:43:19 +08:00 · 2534 次点击
    这是一个创建于 845 天前的主题,其中的信息可能已经有所发展或是发生改变。

    vite.config.ts

    完整的配置我已上传 GitHub ,点击查看

    这是通过这个配置打包好的项目地址 : 演示地址

    https://s4.ax1x.com/2021/12/30/T2YBX6.png

    开启 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>
    
    import MyIcon from './my-icon.svg'
    

    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 的配置,我就先写到这了,至于后面有新的配置,或者有新的变化,我会在这个仓库里面进行配置,以及验证可行性

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1312 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 17:43 · PVG 01:43 · LAX 10:43 · JFK 13:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.