阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > 构建目标与多页面应用配置

构建目标与多页面应用配置

作者:陈川 阅读数:6542人阅读 分类: 构建工具

Vite.js 作为现代前端构建工具,以其极快的启动速度和热更新能力受到开发者青睐。项目配置与基础使用是掌握 Vite 的关键,而构建目标和多页面应用配置则能应对更复杂的场景需求。

项目初始化与基础配置

使用 Vite 创建项目非常简单,通过以下命令即可快速初始化:

npm create vite@latest my-project --template vue

初始化完成后,项目目录中会生成 vite.config.js 文件,这是 Vite 的核心配置文件。基础配置通常包括:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
    open: true
  },
  build: {
    outDir: 'dist'
  }
})

这个基础配置包含了:

  • 插件系统(使用 Vue 插件)
  • 开发服务器配置(端口和自动打开浏览器)
  • 构建输出目录设置

构建目标配置

Vite 支持多种构建目标,可以根据需求输出不同格式的代码:

export default defineConfig({
  build: {
    target: 'es2015',
    outDir: 'dist',
    assetsDir: 'assets',
    emptyOutDir: true,
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`
      }
    }
  }
})

构建目标配置详解:

  • target: 设置最终构建的浏览器兼容目标
  • outDir: 指定输出目录
  • assetsDir: 静态资源存放路径
  • emptyOutDir: 构建前清空输出目录
  • rollupOptions: Rollup 打包配置

针对不同场景,可以设置不同的构建目标:

// 现代浏览器
target: ['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14']

// 兼容旧浏览器
target: ['es2015', 'ie11']

多页面应用配置

Vite 天然支持多页面应用(MPA)配置,相比单页面应用(SPA),MPA 需要更复杂的配置:

import { resolve } from 'path'

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        about: resolve(__dirname, 'about/about.html'),
        contact: resolve(__dirname, 'contact/contact.html')
      }
    }
  }
})

多页面应用的目录结构通常如下:

project/
├── index.html
├── about/
│   ├── about.html
│   └── about.js
├── contact/
│   ├── contact.html
│   └── contact.js
└── vite.config.js

对于更复杂的多页面应用,可以动态生成配置:

import fs from 'fs'
import path from 'path'

function getPageEntries(dir) {
  const pagesDir = path.resolve(__dirname, dir)
  return fs.readdirSync(pagesDir).reduce((entries, page) => {
    const pagePath = path.join(pagesDir, page)
    if (fs.statSync(pagePath).isDirectory()) {
      entries[page] = path.join(pagePath, 'index.html')
    }
    return entries
  }, {})
}

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html'),
        ...getPageEntries('pages')
      }
    }
  }
})

高级多页面配置技巧

对于大型项目,可能需要更精细的控制:

  1. 共享依赖配置
build: {
  rollupOptions: {
    output: {
      manualChunks(id) {
        if (id.includes('node_modules')) {
          return 'vendor'
        }
      }
    }
  }
}
  1. 自定义页面模板
import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
  plugins: [
    createHtmlPlugin({
      pages: [
        {
          entry: 'src/main.js',
          filename: 'index.html',
          template: 'index.html',
          injectOptions: {
            data: {
              title: '首页'
            }
          }
        },
        {
          entry: 'src/about.js',
          filename: 'about.html',
          template: 'about.html',
          injectOptions: {
            data: {
              title: '关于我们'
            }
          }
        }
      ]
    })
  ]
})
  1. 环境变量与多页面结合
// .env
VITE_APP_TITLE=我的应用

// vite.config.js
import { loadEnv } from 'vite'

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  
  return defineConfig({
    plugins: [
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_TITLE
          }
        }
      })
    ]
  })
}

性能优化配置

多页面应用尤其需要注意性能优化:

export default defineConfig({
  build: {
    chunkSizeWarningLimit: 1000,
    cssCodeSplit: true,
    sourcemap: false,
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
})

针对图片等静态资源:

export default defineConfig({
  assetsInclude: ['**/*.glb', '**/*.gltf'],
  build: {
    assetsInlineLimit: 4096 // 4kb以下的文件转为base64
  }
})

开发服务器特殊配置

多页面应用开发时可能需要特殊配置:

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '')
      }
    }
  }
})

热更新配置:

export default defineConfig({
  server: {
    hmr: {
      overlay: false
    }
  }
})

与其他工具集成

Vite 可以与其他工具无缝集成:

  1. 与 Tailwind CSS 集成
export default defineConfig({
  css: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer')
      ]
    }
  }
})
  1. 与 SVG 组件集成
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]'
    })
  ]
})
  1. 与 PWA 集成
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico', 'apple-touch-icon.png'],
      manifest: {
        name: 'My App',
        short_name: 'App',
        start_url: '/',
        display: 'standalone',
        background_color: '#ffffff',
        theme_color: '#000000',
        icons: [
          {
            src: 'pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png'
          }
        ]
      }
    })
  ]
})

常见问题解决方案

  1. 路由冲突问题
// vite.config.js
export default defineConfig({
  server: {
    historyApiFallback: {
      rewrites: [
        { from: /^\/about/, to: '/about/index.html' },
        { from: /^\/contact/, to: '/contact/index.html' }
      ]
    }
  }
})
  1. 静态资源路径问题
export default defineConfig({
  base: '/my-app/',
  build: {
    assetsDir: 'static'
  }
})
  1. 环境变量使用问题
// .env
VITE_API_URL=https://api.example.com

// 组件中使用
const apiUrl = import.meta.env.VITE_API_URL
  1. 多页面CSS提取问题
export default defineConfig({
  build: {
    cssCodeSplit: true,
    rollupOptions: {
      output: {
        assetFileNames: 'assets/[name].[ext]'
      }
    }
  }
})

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌