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

2021-12-30 08:43:19 +08:00
 vipbic

vite.config.ts

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

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

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

2546 次点击
所在节点    分享创造
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/825195

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX