例子,vue3导入element-plus

打包大小

 

1.加载插件cdn-import

yarn add vite-plugin-cdn-import -D

2.配置vite

vite.config.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { autoComplete, Plugin as importToCDN } from "vite-plugin-cdn-import";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    importToCDN({
      modules: [
        autoComplete("vue"),
        {
          name: "element-plus",
          var: "ElementPlus", // 根据main.ts中定义的来
          path: "https://unpkg.com/element-plus@2.2.28/dist/index.full.js",
          css: "https://unpkg.com/element-plus@2.2.28/dist/index.css",
        },
      ],
    }),
  ],
});

3.更改element-plus导入

import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";

import ElementPlus from "element-plus";
// import "element-plus/dist/index.css"; // 删除css引入用cdn,避免重复引入

createApp(App).use(ElementPlus).mount("#app");

打包大小

 

vite 还可以打包时对文件进行压缩

1.加载compression插件

yarn add vite-plugin-compression -D

2.配置vite

vite.config.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { autoComplete, Plugin as importToCDN } from "vite-plugin-cdn-import";
import viteCompression from "vite-plugin-compression";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    importToCDN({
      modules: [
        autoComplete("vue"),
        {
          name: "element-plus",
          var: "ElementPlus", // 根据main.ts中定义的来
          path: "https://unpkg.com/element-plus@2.2.28/dist/index.full.js",
          css: "https://unpkg.com/element-plus@2.2.28/dist/index.css",
        },
      ],
    }),
    viteCompression({
      verbose: true,
      disable: false,
      deleteOriginFile: true,
      // 对于大于1M的文件进行压缩
      // threshold: 1024000,
      algorithm: "gzip",
      ext: "gz",
    }),
  ],
});

打包结果

 

同时记得开启nginx 压缩算法的功能

server{
    #gzip
    #开启gzip功能
    gzip on;
    #开启gzip静态压缩功能
    gzip_static on;
    #gzip缓存大小
    gzip_buffers 4 16k;
    #gzip http版本
    gzip_http_version 1.1;
    #gzip 压缩级别 1-10
    gzip_comp_level 5;
    #gzip 压缩类型
    gzip_types text/plain...;
    gzip_vary on;
}

Logo

前往低代码交流专区

更多推荐