使用vue3 vite构建项目,优化性能,拆分包,减小主包js的

2023-06-20  本文已影响0人  戚培俊

打包内存占用优化

配置build参数,设置打包占用内存,可以提升打包速度,优化内存占用
•package.json

"scripts": {
    ...
    "build": "node --max_old_space_size=4096 ./node_modules/vite/bin/vite.js build",
  },

build 优化

•vite.config.js

const dependencies = require('./package.json').dependencies;
export default defineConfig({
  ...
  // 打包配置
    build: {
        outDir: 'you-out-dir',
        assetsDir: 'static',
        brotliSize: false, // 设置为false将禁用构建的brotli压缩大小报告。可以稍微提高构建速度
        minify: true, // 开启压缩
        rollupOptions: {
            treeshake: true, // 开启 Tree Shaking,消除未使用的代码,减小最终的包大小
            output: {
                // 根据不同的js库 拆分包,减少index.js包体积
                manualChunks(id) {
                    if (id.includes('node_modules')) {
                        // 指定需要拆分的第三方库或模块
                        console.info('id', id)
                        const dependenciesKeys = Object.keys(dependencies);
                        const match = dependenciesKeys.find((item) => {
                            return id.includes(item);
                        });
                        console.info('match', match)
                        const notSplit = ['vue', 'ant-design-vue'];
                        if (match && !notSplit.includes(match)) {
                            return match;
                        }
                    }
                },
            },
            commonjsOptions: {
                requireReturnsDefault: 'namespace', // 要求ES模块返回其名称空
            }
        },
    },
})

优化前

image.png

优化后

image.png
上一篇 下一篇

猜你喜欢

热点阅读