阿里云主机折上折
  • 微信号
Current Site:Index > Output generation phase control

Output generation phase control

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

Output Generation Phase Control

Vite.js employs different strategies for handling resource output in development and production environments. In development mode, it relies on native browser ESM for on-demand compilation, while production builds use Rollup for full bundling. This differentiated processing mechanism makes output control a critical aspect of project optimization.

Basic Configuration Methods

Basic output behavior can be defined in vite.config.js:

// vite.config.js
export default defineConfig({
  build: {
    outDir: 'dist',
    assetsDir: 'static',
    emptyOutDir: true
  }
})
  • outDir specifies the output directory (default: dist)
  • assetsDir sets the static assets subdirectory (default: assets)
  • emptyOutDir controls whether to empty the output directory

File Hashing and Cache Strategy

Production builds automatically add hash suffixes to resource files:

build: {
  rollupOptions: {
    output: {
      assetFileNames: 'static/[name]-[hash].[ext]',
      chunkFileNames: 'static/[name]-[hash].js',
      entryFileNames: 'static/[name]-[hash].js'
    }
  }
}

Generate a resource manifest with build.manifest:

build: {
  manifest: true,
  rollupOptions: {
    output: {
      manualChunks(id) {
        if (id.includes('node_modules')) {
          return 'vendor'
        }
      }
    }
  }
}

Multi-Page Application Output Control

Special configuration is required for multi-entry projects:

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

Custom Output Formats

Modify output structure using Rollup plugins:

import { viteStaticCopy } from 'vite-plugin-static-copy'

export default defineConfig({
  plugins: [
    viteStaticCopy({
      targets: [
        { src: 'public/robots.txt', dest: './' }
      ]
    })
  ]
})

Environment Variable Injection

Dynamically control output content:

// .env.production
VITE_API_BASE=https://api.example.com

// Usage in components
const apiBase = import.meta.env.VITE_API_BASE

Code Splitting Optimization

Fine-tuned chunk splitting strategy:

build: {
  chunkSizeWarningLimit: 1000,
  rollupOptions: {
    output: {
      manualChunks(id) {
        if (id.includes('lodash')) {
          return 'lodash'
        }
        if (id.includes('chart.js')) {
          return 'charts'
        }
      }
    }
  }
}

Resource Inlining

Inline small files to reduce requests:

build: {
  assetsInlineLimit: 4096 // Files under 4KB converted to base64
}

Output Preprocessing

Modify final output with plugins:

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

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

Build Artifact Analysis

Visualize output structure:

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

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

Dynamic Loading Control

Configure async component loading behavior:

// Component definition
const LazyComponent = defineAsyncComponent({
  loader: () => import('./HeavyComponent.vue'),
  loadingComponent: LoadingSpinner,
  delay: 200,
  timeout: 3000
})

Server-Side Rendering Output

Special configuration for SSR builds:

build: {
  ssr: true,
  rollupOptions: {
    input: 'src/entry-server.js'
  }
}

Output Validation Mechanism

Add post-build verification steps:

import checker from 'vite-plugin-checker'

export default defineConfig({
  plugins: [
    checker({
      typescript: true,
      eslint: {
        lintCommand: 'eslint "./src/**/*.{js,ts,vue}"'
      }
    })
  ]
})

Multi-Environment Output Differences

Adjust output based on environment variables:

build: {
  minify: isProduction ? 'terser' : false,
  sourcemap: isDevelopment ? 'inline' : false
}

Output Path Rewriting

Handle deployment path issues:

export default defineConfig({
  base: process.env.NODE_ENV === 'production' 
    ? '/production-sub-path/' 
    : '/'
})

Build Time Optimization

Parallel processing for faster output:

import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    })
  ],
  build: {
    target: 'es2015',
    cssTarget: 'chrome80'
  }
})

Output Format Conversion

Handle special format requirements:

import { vitePlugin as utwm } from 'unplugin-transform-web-monetization'

export default defineConfig({
  plugins: [
    utwm({
      paymentPointer: '$ilp.example.com/123456789'
    })
  ]
})

Build Event Hooks

Insert custom operations during output phase:

export default defineConfig({
  plugins: [{
    name: 'log-build-complete',
    closeBundle() {
      console.log('Build completed at', new Date().toISOString())
    }
  }]
})

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.