当前位置:   article > 正文

记录一次Vite打包优化_vite-plugin-spritesmith

vite-plugin-spritesmith

一、公共资源CDN引入

// npm install vite-plugin-cdn-import --save-dev
// cdnImport.ts
import importToCDN from 'vite-plugin-cdn-import'

export default function createImportCDN() {
    return importToCDN({
        modules: [
            {
                name: 'vue',
                var: 'Vue',
                path: 'https://cdn.jsdelivr.net/npm/vue@3.2.38/dist/vue.global.prod.js'
            },
            {
                name: 'vue-router',
                var: 'VueRouter',
                path: 'https://unpkg.com/vue-router@4.1.5/dist/vue-router.global.prod.js'
            },

            {
                name: 'element-plus',
                var: 'ElementPlus',
                path: `https://unpkg.com/element-plus@2.2.36/dist/index.full.js`,
                css: 'https://unpkg.com/element-plus/dist/index.css'
            },
            // vue-demi是让pinia判断是v2还是v3
            {
                name: 'vue-demi',
                var: 'VueDemi',
                path: 'https://cdn.bootcdn.net/ajax/libs/vue-demi/0.13.11/index.iife.js'
            },
            {
                name: 'pinia',
                var: 'Pinia',
                path: 'https://cdn.bootcdn.net/ajax/libs/pinia/2.0.32/pinia.iife.prod.min.js'
            },
            {
                name: 'echarts',
                var: 'Echarts',
                path: 'https://cdn.bootcdn.net/ajax/libs/echarts/5.3.2/echarts.min.js'
            }
        ]
    })
}
// vite/index.ts
import createImportCDN from './cdnImport'
export default function createVitePlugins() {
    vitePlugins.push(createImportCDN())
    return vitePlugins
}


//vite.config.js
import { defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite'
export default defineConfig(({ mode, command }) => {
  return {
    plugins: createVitePlugins(),
    build: {
      rollupOptions: {
        external: ['vue', 'pinia', 'vue-router', 'element-plus', 'echarts'],
      },
    },
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

二 、echarts按需加载

// echarts.ts
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入各种图表,图表后缀都为 Chart
import {
    BarChart,
    PieChart,
    MapChart,
    LineChart,
    LinesChart,
    ScatterChart
} from 'echarts/charts';
// 引入提示框,标题,直角坐标系等组件,组件后缀都为 Component
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    PolarComponent
    // GeoCoComponent
} from 'echarts/components';
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import {
    CanvasRenderer
} from 'echarts/renderers';

// 注册必须的组件
echarts.use(
    [
        TitleComponent,
        TooltipComponent,
        GridComponent,
        LegendComponent,
        BarChart,
        CanvasRenderer,
        PieChart,
        LineChart,
        MapChart,
        LinesChart,
        ScatterChart,
        PolarComponent
    ]
)

export default echarts

// main.js
import { createApp } from 'vue'
import echarts from './utils/echarts'
const app = createApp(App)
// 实例挂载全局
app.config.globalProperties.$echarts = echarts;

// index.vue
<template>
  <div class="echarts-box">
    <div id="myEcharts" :style="{ width: '900px', height: '900px' }"></div>
  </div>
</template>

import {  onMounted, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;

onMounted(() => {
  echartInit();
});

const echartInit = () => {
  //获取DOM元素并初始化
  var myChart = proxy.$echarts.init(document.getElementById("myEcharts"));
  // 指定图表的配置项和数据
  var option = {
  };
  myChart.setOption(option);
  // 解决第一次显示正常路由跳转后echarts不显示图表的问题
  document.getElementById("myEcharts").setAttribute("_echarts_instance_", "");
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

三、vite-plugin-imagemin图片压缩

// 因为vite-plugin-imagemin是国外插件 使用npm安装会出现问题
// 解决办法是 在package.json文件中加入
  "resolutions": {
    "bin-wrapper": "npm:bin-wrapper-china"
  }
// 在使用 yarn add vite-plugin-imagemin -D 进行安装

// viteImage.ts
import viteImagemin from 'vite-plugin-imagemin' // 引入

export default function createViteImage() {
    return viteImagemin({
        gifsicle: {
            optimizationLevel: 7,
            interlaced: false,
        },
        optipng: {
            optimizationLevel: 7,
        },
        mozjpeg: {
            quality: 20,
        },
        pngquant: {
            quality: [0.8, 0.9],
            speed: 4,
        },
        svgo: {
            plugins: [
                {
                    name: 'removeViewBox',
                },
                {
                    name: 'removeEmptyAttrs',
                    active: false,
                },
            ],
        },
    })
}
// vite/index.ts
import { defineConfig, loadEnv } from 'vite'
import createViteImage from './viteImage'
export default function createVitePlugins() {
    vitePlugins.push(createViteImage())
    return vitePlugins
}
//vite.config.js
import createVitePlugins from './vite'
export default defineConfig(({ mode, command }) => {
  return {
    plugins: createVitePlugins(),
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

四、vite-plugin-compression进行gzip压缩

 // npm install vite-plugin-compression -D
 // compression.js
import compressPlugin from "vite-plugin-compression";

export default function configCompressPlugin(env) {
    const { VITE_BUILD_COMPRESS } = env
    const plugin = []
    if (VITE_BUILD_COMPRESS) {
        const compressList = VITE_BUILD_COMPRESS.split(',')
        if (compressList.includes('gzip')) {
            plugin.push(
                compressPlugin({
                    ext: '.gz',
                    deleteOriginFile: false
                })
            )
        }
        if (compressList.includes('brotli')) {
            plugin.push(
                compressPlugin({
                    ext: '.br',
                    algorithm: 'brotliCompress',
                    deleteOriginFile: false
                })
            )
        }
    }
    return plugin
}

// vite/index.ts
import configCompressPlugin from './compression'
export default function createVitePlugins(viteEnv, isBuild = false) {
    isBuild && vitePlugins.push(...configCompressPlugin(viteEnv))
    return vitePlugins
}

//vite.config.js
import { defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite'
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV } = env
  return {
    plugins: createVitePlugins(env, command === 'build'),
})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

五、常规配置

import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite'

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV } = env
  return {
    base: VITE_APP_ENV === 'production' ? './' : '/',
    plugins: createVitePlugins(env, command === 'build'), 	//自定义插件
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    server: {
      port: 80,
      open: true,
      host: '0.0.0.0'
    },
    build: {
      chunkSizeWarningLimit: 1500,
      minify: 'terser',	// 使用前需要进行 npm install terser
      terserOptions: {
      	// 清除debugger及console.log的打印信息
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          // 分类输出
          chunkFileNames: 'js/[name]-[hash].js', 
          entryFileNames: 'js/[name]-[hash].js',
          // assetFileNames: '[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) { // 超大静态资源拆分
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        },
        // 打包时要忽略的外部依赖
        external: ['vue', 'pinia', 'vue-router', 'element-plus', 'echarts'],
      },
    },
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/392857
推荐阅读
相关标签
  

闽ICP备14008679号