阿里云主机折上折
  • 微信号
Current Site:Index > Build output directory structure control

Build output directory structure control

Author:Chuan Chen 阅读数:21357人阅读 分类: 构建工具

Project Configuration and Basic Usage

Vite.js provides highly flexible build options through its configuration file vite.config.js. By default, the vite.config.js file in the project root directory is automatically loaded. The basic configuration structure is as follows:

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

export default defineConfig({
  // configuration options
})

Common basic configurations include development server settings, build options, and environment variable handling. For example, setting the development server port:

export default defineConfig({
  server: {
    port: 3000,
    open: true
  }
})

Environment variables are managed through .env files, and Vite automatically loads variables from .env files:

# .env
VITE_API_URL=https://api.example.com

In code, access the variable via import.meta.env.VITE_API_URL:

const apiUrl = import.meta.env.VITE_API_URL

Controlling Build Output Directory Structure

Vite's default build output directory is dist, which can be modified via build.outDir:

export default defineConfig({
  build: {
    outDir: 'build'
  }
})

Static Asset Handling

Static assets are copied to the root level of the output directory by default. Use build.assetsDir to specify a subdirectory for static assets:

export default defineConfig({
  build: {
    assetsDir: 'static'
  }
})

With this configuration, all static assets will be placed in the dist/static directory.

File Hashing and Naming

Vite adds hashes to static asset filenames by default for long-term caching:

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        assetFileNames: 'static/[name]-[hash][extname]',
        chunkFileNames: 'static/[name]-[hash].js',
        entryFileNames: 'static/[name]-[hash].js'
      }
    }
  }
})

Multi-Page Application Directory Structure

For multi-page applications, different directory structures can be achieved through configuration:

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

This generates two entry points corresponding to different HTML files.

Custom Build Logic

Use the build.lib option to build in library mode, controlling the output format and filenames:

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, 'lib/main.js'),
      name: 'MyLib',
      fileName: (format) => `my-lib.${format}.js`
    }
  }
})

Path Alias Configuration

Path aliases simplify import statements and affect build output:

import { resolve } from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
})

Then, in code, you can use:

import Component from '@/components/Component.vue'

Public Base Path

When deploying to a non-root directory, configure the base option:

export default defineConfig({
  base: '/sub-path/'
})

This affects the path prefix for all resource references.

Build Target Configuration

Use build.target to specify browser compatibility for the build output:

export default defineConfig({
  build: {
    target: 'es2015'
  }
})

Code Splitting Strategy

Vite supports multiple code splitting strategies:

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue', 'vue-router'],
          utils: ['lodash', 'axios']
        }
      }
    }
  }
})

Custom HTML Output

Plugins allow full control over HTML output structure:

import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
  plugins: [
    createHtmlPlugin({
      minify: true,
      inject: {
        data: {
          title: 'My App'
        }
      }
    })
  ]
})

Environment-Specific Configuration

Load different configurations based on the environment:

export default defineConfig(({ command, mode }) => {
  if (command === 'serve') {
    return {
      // development environment configuration
    }
  } else {
    return {
      // production environment configuration
    }
  }
})

Build Analysis

Use plugins to analyze build output size:

import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
  plugins: [
    visualizer({
      open: true,
      filename: 'stats.html'
    })
  ]
})

Source Map Configuration

Control source map generation behavior:

export default defineConfig({
  build: {
    sourcemap: true // or 'inline'/'hidden'
  }
})

External Dependency Handling

Exclude certain dependencies from the build:

export default defineConfig({
  build: {
    rollupOptions: {
      external: ['jquery']
    }
  }
})

Multi-Format Output

Generate multiple module formats simultaneously:

export default defineConfig({
  build: {
    rollupOptions: {
      output: [
        { format: 'es', dir: 'dist/es' },
        { format: 'cjs', dir: 'dist/cjs' }
      ]
    }
  }
})

Build Hooks

Use build hooks for further customization:

export default defineConfig({
  plugins: [
    {
      name: 'custom-hooks',
      closeBundle() {
        // operations to perform after build completion
      }
    }
  ]
})

Filesystem Cache

Configure build cache location:

export default defineConfig({
  cacheDir: './node_modules/.vite'
})

Build Reports

Generate build size reports:

export default defineConfig({
  build: {
    brotliSize: true,
    chunkSizeWarningLimit: 1000
  }
})

Custom Middleware

Add custom middleware to the development server:

export default defineConfig({
  server: {
    middlewareMode: true,
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        // custom middleware logic
      })
    }
  }
})

Build Time Optimization

Reduce build time through configuration:

export default defineConfig({
  optimizeDeps: {
    include: ['vue', 'vue-router']
  }
})

Multi-Environment Variable Files

Support variable files for different environments:

.env.development
.env.production
.env.staging

Vite automatically loads the corresponding environment file based on the current mode.

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

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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.