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放在一个目录下 图片在在一个目录下

相关推荐
baiduopenmap几秒前
百度世界2024精选公开课:基于地图智能体的导航出行AI应用创新实践
前端·人工智能·百度地图
hopetomorrow1 分钟前
学习路之压力测试--jmeter安装教程
学习·jmeter·压力测试
hopetomorrow2 分钟前
学习路之PHP--使用GROUP BY 发生错误 SELECT list is not in GROUP BY clause .......... 解决
开发语言·学习·php
请叫我欧皇i20 分钟前
html本地离线引入vant和vue2(详细步骤)
开发语言·前端·javascript
533_23 分钟前
[vue] 深拷贝 lodash cloneDeep
前端·javascript·vue.js
guokanglun29 分钟前
空间数据存储格式GeoJSON
前端
/**书香门第*/30 分钟前
Cocos creator 3.8 支持的动画 7
学习·游戏·游戏引擎·游戏程序·cocos2d
美式小田1 小时前
单片机学习笔记 9. 8×8LED点阵屏
笔记·单片机·嵌入式硬件·学习
zhang-zan1 小时前
nodejs操作selenium-webdriver
前端·javascript·selenium
ZBY520311 小时前
【Vue】 npm install amap-js-api-loader指南
javascript·vue.js·npm