vue3

vite.config.js配置

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import svgLoader from "vite-svg-loader";
import Markdown from "vite-plugin-md";
import { VitePWA } from "vite-plugin-pwa";
import NutUIResolver from "@nutui/nutui/dist/resolver";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import { viteMockServe } from "vite-plugin-mock"; // mock会导致本地启动速度变慢
import basicSsl from '@vitejs/plugin-basic-ssl' //本地https配置

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    <!--viteCompression({-->
    <!--  algorithm: 'gzip', // 使用 gzip 压缩-->
    <!--  threshold: 10240, // 超过 10KB 的文件才会压缩-->
    <!--  ext: '.gz', // 压缩文件的扩展名-->
    <!--}),-->

    basicSsl(),
    AutoImport({
      include: [
        /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
        /\.vue$/,
        /\.vue\?vue/, // .vue
        /\.md$/, // .md
      ],

      imports: [
        "vue",
        "vue-router",
        {
          "@vueuse/core": [
            "useMouse", // import { useMouse } from '@vueuse/core',
            ["useFetch", "useMyFetch"], // import { useFetch as useMyFetch } from '@vueuse/core',
          ],
          axios: [
            ["default", "axios"], // import { default as axios } from 'axios',
          ],
          "[package-name]": ["[import-names]", ["[from]", "[alias]"]],
        },
      ],

      eslintrc: {
        enabled: false, // Default `false`
        filepath: "./.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
    }),
    Components({
      // relative paths to the directory to search for components.
      dirs: ["src/components"],

      // valid file extensions for components.
      extensions: ["vue"],
      // search for subdirectories
      deep: true,

      // generate `components.d.ts` global declarations,
      // also accepts a path for custom filename
      dts: false,

      // Allow subdirectories as namespace prefix for components.
      directoryAsNamespace: false,
      // Subdirectory paths for ignoring namespace prefixes
      // works when `directoryAsNamespace: true`
      globalNamespaces: [],

      // auto import for directives
      // default: `true` for Vue 3, `false` for Vue 2
      // Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
      // To install Babel, run: `npm install -D @babel/parser @babel/traverse`
      directives: true,

      // filters for transforming targets
      include: [/\.vue$/, /\.vue\?vue/],
      exclude: [
        /[\\/]node_modules[\\/]/,
        /[\\/]\.git[\\/]/,
        /[\\/]\.nuxt[\\/]/,
      ],
      resolvers: [NutUIResolver()],
    }),
    svgLoader(),
    vue({
      include: [/\.vue$/, /\.md$/],
    }),
    Markdown(),
    viteMockServe({
      supportTs: false,
    }),
    VueSetupExtend(),
    VitePWA({
      includeAssets: ["favicon.svg"],
      registerType: "autoUpdate",
      workbox: {
        runtimeCaching: [
          {
            urlPattern: /someInterface/i, // 接口缓存 此处填你想缓存的接口正则匹配
            handler: "CacheFirst",
            options: {
              cacheName: "interface-cache",
            },
          },
          {
            urlPattern: /(.*?)\.(js|css|ts)/, // js /css /ts静态资源缓存
            handler: "CacheFirst",
            options: {
              cacheName: "js-css-cache",
            },
          },
          {
            urlPattern: /(.*?)\.(png|jpe?g|svg|gif|bmp|psd|tiff|tga|eps)/, // 图片缓存
            handler: "CacheFirst",
            options: {
              cacheName: "image-cache",
            },
          },
        ],
      },

      base: "/",
      srcDir: "src",
      filename: "sw.js",
      strategies: "injectManifest",
      manifest: {
        name: "Test Project",
        short_name: "Test",
        theme_color: "#ffffff",
        start_url: "/",
        display: "standalone",
        background_color: "#ffffff",
        icons: [
          {
            src: "icon-192.png",
            sizes: "192x192",
            type: "image/png",
          },
          {
            src: "/icon-512.png",
            sizes: "512x512",
            type: "image/png",
          },
          {
            src: "icon-512.png",
            sizes: "512x512",
            type: "image/png",
            purpose: "any maskable",
          },
        ],
      },
    }),
  ],

  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
          @import "@/assets/css/variables.scss";
          @import "@/assets/css/mixins.scss";
          @import "@nutui/nutui/dist/styles/variables.scss";
        `,
        javascriptEnabled: true,
      },
    },
  },

  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"), // 把 @ 指向到 src 目录去
      "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js",
    },
  },

  server: {
    host: true, // host设置为true才可以使用network的形式,以ip访问项目
    port: 8888, // 端口号
    open: true, // 自动打开浏览器
    cors: true, // 跨域设置允许
    strictPort: false, // 如果设置true,端口已占用直接退出
    hmr: {
      overlay: false, // 禁用错误的全屏覆盖提示
    },
    // 接口代理
    proxy: {
      "/api": {
        // 本地 8888 前端代码的接口 代理到 8000 的服务端口
        target: "http://localhost:8000/",
        changeOrigin: true, // 允许跨域
        rewrite: (path) => path.replace("/api/", "/"),
      },
      "/api/v1": {
        target: "http://localhost:8000/",
        changeOrigin: true,
        rewrite: (path) => path.replace("/^/api/v1", ""),
      },
    },
  },
  optimizeDeps: {
    include: ['axios', 'lodash'], // 强制预构建的依赖
    exclude: ['some-large-lib'], // 排除不需要预构建的依赖
  },

  // 静态资源处理
  assetsInclude: ['**/*.gltf', '**/*.glb'], // 自定义资源类型
  build: {
    brotliSize: false,
    // 消除打包大小超过500kb警告
    chunkSizeWarningLimit: 2000,
    // 在生产环境移除console.log
    terserOptions: {
      compress: {
        drop_console: false,
        pure_funcs: ["console.log", "console.info"],
        drop_debugger: true,
      },
    },
    assetsDir: "static/assets",
    // target: 'modules',
    minify: "terser", // 混淆器,terser构建后文件体积更小
    // 静态资源打包到dist下的不同目录
    rollupOptions: {
      output: {
      manualChunks(id) {
        // 将第三方依赖打包到 vendor.js
        //if (id.includes('node_modules')) {
        //    return 'vendor';
        //}
        //},

        chunkFileNames: "static/js/[name]-[hash].js",
        entryFileNames: "static/js/[name]-[hash].js",
        assetFileNames: "static/[ext]/[name]-[hash].[ext]",
      },
    },
  },
});

上次更新: