vite 打包 学习

bash 复制代码
plugins.js

import vue from "@vitejs/plugin-vue";
// 自动引入插件
import autoImport from "unplugin-auto-import/vite";
import setupExtend from "unplugin-vue-setup-extend-plus/vite";
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
// gzip 插件
import compression from "vite-plugin-compression";
// 查看 打包文件大小 插件
import { visualizer } from 'rollup-plugin-visualizer'

export default function getVitePlugins(command) {
// 这个值在package.js 中 不同的打包方式修改这个值
  const isAnalyze = process.env.ANALYZE === 'true';

  return [
    vue(),
    autoImport({
      // Auto import functions from Vue, e.g. ref, reactive, toRef...
      // 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
      imports: ["vue", "vue-router", "pinia"],
      // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
      // 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式)
      resolvers: [
        ElementPlusResolver()
      ],
      dts: false,
    }),
    command === "build"
      ? compression({
          ext: ".gz",
          deleteOriginFile: false,
        })
      : null,
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    setupExtend({}),
    isAnalyze ? visualizer({
      open: true,
      filename: 'visualizer.html' //分析图生成的文件名
    }) : null
  ];
}
bash 复制代码
vite.config.js
import { defineConfig,loadEnv } from 'vite'
import path from "path";
import getVitePlugins from './vite/plugins.js'
// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    resolve: {
      alias: {
        // 设置别名
        "@": path.resolve(__dirname, "./src"),
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    plugins: [getVitePlugins(command)],
    base: env.VITE_ENV === "production" ? "./" : "/", // 公共基础路径 相当于 webpack的output.publicPath
    build: {
      outDir: 'dist/static',  // 打包输出目录
      rollupOptions: {
        output: {
          entryFileNames: "js/[name]-[hash].js",  // 入口文件名
          chunkFileNames: "js/[name]-[hash].js", // 代码分割文件名
          assetFileNames(assetInfo) { // 根据后缀名匹配 资源文件名
            if (assetInfo.name.endsWith(".css")) {
              return "css/[name]-[hash].css";
            }
            const imgExts = [".png", ".jpg", ".jpeg", ".gif", ".svg", '.webp', '.ico'];
            if (imgExts.some(ext => assetInfo.name.endsWith(ext))) {
              return "img/[name]-[hash].[ext]";
            }
            return "assets/[name]-[hash].[ext]";
          },
          // 将不同的模块放在不同的chunk中
          manualChunks: (id) => {
            if (id.includes('node_modules')) {
              // if (id.includes('vue')) return 'vendor-vue';
              if (id.includes('lodash')) return 'vendor-lodash';
              if (id.includes('element-plus')) return 'vendor-element';
              if (id.includes('axios')) return 'vendor-axios';
              if (id.includes('leafer-ui')) return 'vendor-leafer';
              return 'vendor-other';
            }
            // 根据你的具体需求调整这里的逻辑
            return 'main';
          },
        }
      }
    }
  }

})
bash 复制代码
main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

let app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}


app.use(router)
app.mount('#app')
bash 复制代码
package.js

cross-env 是用来 判断环境变量的 "build:test": "cross-env ANALYZE=true vite build" 
修改了ANALYZE 的值  
这样的话 npm run build 就是正常的打包
npm run build:test 打包完 就会生成打包分析的网页 并打开
{
  "name": "vite-project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "build:test": "cross-env ANALYZE=true vite build"
  },
  "dependencies": {
    "@element-plus/icons-vue": "2.3.1",
    "axios": "^1.7.5",
    "cross-env": "^7.0.3",
    "element-plus": "^2.8.1",
    "leafer-ui": "^1.0.2",
    "less": "^4.2.0",
    "lodash": "^4.17.21",
    "pinia": "^2.2.2",
    "sass": "^1.77.8",
    "vue": "^3.4.37",
    "vue-router": "^4.4.3"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.1.2",
    "rollup-plugin-visualizer": "^5.12.0",
    "unplugin-auto-import": "0.17.1",
    "unplugin-vue-components": "^0.27.4",
    "unplugin-vue-setup-extend-plus": "1.0.0",
    "vite": "^5.4.1",
    "vite-plugin-compression": "0.5.1"
  }
}

打包结果

打包后的目录

将js放在一个目录下 css放在一个目录下 图片在在一个目录下

相关推荐
Aision_1 小时前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
剑飞的编程思维1 小时前
真实学习本质-坚持思考的人
学习
AI浩1 小时前
学习嵌入位置:面向小目标检测查询检索的噪声感知位置编码
人工智能·学习·目标检测
倾颜3 小时前
从 textarea 到 AI 输入框:用 Tiptap 实现 / 命令、@ 引用和结构化请求
前端·langchain·next.js
kyriewen5 小时前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
kyriewen5 小时前
你写的代码没有测试,就像出门不锁门——Jest + Testing Library 从入门到不慌
前端·单元测试·jest
辞旧 lekkk5 小时前
【Qt】信号和槽
linux·开发语言·数据库·qt·学习·mysql·萌新
yuzhiboyouye6 小时前
web前端英语面试
前端·面试·状态模式
canonical_entropy7 小时前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月7 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构