Production Environment Build Commands and Configuration
Production Build Command
Vite’s production build is executed using the vite build command, which compiles the project into static assets suitable for production based on the configuration in vite.config.js. By default, the build output is placed in the dist directory.
# Build for production
vite buildConfiguring vite.config.js
The vite.config.js file controls various aspects of the build process. Below are key configuration options particularly relevant for production builds:
base: Sets the public base path for the project, crucial for sites deployed under subpaths.
export default {
base: '/my-app/',
};build: Manages multiple aspects of the build process, including output directory, asset directory, code compression, and CSS handling.
export default {
build: {
outDir: 'build', // Output directory
assetsDir: 'static', // Static assets directory
rollupOptions: { /* Rollup configuration */ },
minify: 'terser', // Code compressor
cssCodeSplit: true, // Enable CSS code splitting
brotliSize: true, // Calculate Brotli-compressed file sizes
sourcemap: false, // Disable source maps
},
};rollupOptions: Customizes Rollup build options, such as controlling code splitting and plugin usage.
export default {
build: {
rollupOptions: {
input: 'index.html', // Specify input file
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
},
},
},
},
};Code Compression and Optimization
Production builds automatically enable code compression and optimization to reduce file sizes and improve load times. Vite supports two compression methods:
terser: Suitable for JavaScript and HTML.esbuild: Faster compression, suitable for JavaScript.
export default {
build: {
minify: 'terser', // Or 'esbuild'
},
};Asset Optimization
Vite automatically compresses and converts static assets like images and fonts to optimize network transfer. You can control the size threshold for inlining assets using build.assetsInlineLimit.
export default {
build: {
assetsInlineLimit: 4096, // Inline assets smaller than 4KB
},
};Code Splitting and Lazy Loading
Vite supports automatic code splitting using dynamic imports (import()) to enable on-demand loading, reducing initial load times.
// Use dynamic import in a component
const MyComponent = () => import('./MyComponent.vue');Deployment and Cache Control
After building, deploy the dist directory to a server. To enhance performance, leverage CDNs and browser caching. Use hashed filenames from the manifest.json file in index.html for cache control:
<!-- index.html -->
<script src="/static/js/main.[hash].js"></script>
<link rel="stylesheet" href="/static/css/main.[hash].css">Environment Variables and Multi-Environment Builds
Vite supports reading environment variables from .env files, which are critical in production for managing sensitive information like database connections and API endpoints. Use the define method in vite.config.js to inject environment variables.
// vite.config.js
export default {
define: {
'process.env.API_URL': JSON.stringify(process.env.API_URL),
},
};Optimization Strategies
Tree Shaking
Tree Shaking is a code elimination technique that removes unused exports and code to reduce the final bundle size. ES6 module syntax (import and export) provides a solid foundation for Tree Shaking, enabling static analysis to identify used and unused code.
How It Works
Vite leverages Rollup and ESBuild’s Tree Shaking capabilities to analyze the project’s dependency graph during the build process, removing unused code.
Example
Consider the following module:
// myModule.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;When only the add function is used:
// main.js
import { add } from './myModule';
console.log(add(1, 2));After the build, the subtract function is removed via Tree Shaking since it is unused.
Configuration
Tree Shaking is enabled by default in Vite, requiring no additional configuration. However, in some cases, you may need to disable or adjust Tree Shaking behavior using rollupOptions in vite.config.js.
// vite.config.js
export default {
build: {
rollupOptions: {
treeshake: {
moduleSideEffects: false, // Enable more aggressive Tree Shaking
},
},
},
};Code Splitting
Code Splitting divides the application into smaller bundles to enable on-demand loading, reducing initial load times.
How It Works
Vite automatically performs code splitting using dynamic imports (import()), splitting large modules into smaller, lazily loaded chunks.
Example
// main.js
const loadComponent = async () => {
const Component = await import('./MyComponent.vue');
// Use Component
};
loadComponent();In this example, MyComponent.vue is not loaded immediately on page load but only when loadComponent is called.
Configuration
Control code splitting behavior using rollupOptions in vite.config.js:
// vite.config.js
export default {
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
},
},
},
},
};This configuration splits dependencies from node_modules into separate chunks.
Other Optimization Strategies
In addition to Tree Shaking and Code Splitting, Vite offers other optimization techniques:
- Minification: Compresses and obfuscates code using Terser or ESBuild.
- Asset Optimization: Compresses and converts static assets like images and fonts.
- Bundling Strategies: Adjusts bundling via
build.rollupOptionsinvite.config.js, controlling chunk sizes and naming.
Best Practices
- Use ES6 Module Syntax: Ensure your project uses ES6 module syntax, the foundation for Tree Shaking and Code Splitting.
- Dynamic Imports: Use dynamic imports (
import()) to defer loading non-critical code. - Optimize Configuration: Tailor
vite.config.jssettings to achieve optimal build results based on project needs. - Test and Validate: Use tools like Webpack Bundle Analyzer or Chrome DevTools’ Network panel to analyze and optimize build outputs.
Static Asset Handling and CDN Integration
Asset Referencing
In Vite, static assets can be referenced like modules, and Vite automatically handles their loading and bundling.
Asset References in CSS
In CSS, use the url() function to reference images and other assets, with Vite handling path resolution and bundling.
/* styles.css */
.background-image {
background-image: url('./images/bg.jpg');
}Asset References in Vue SFCs
In Vue Single File Components (SFCs), reference assets directly in templates, and Vite converts them to import statements.
<template>
<img :src="require('@/assets/logo.png')" alt="Logo" />
</template>Asset Inlining
Vite allows configuring asset inlining strategies. Smaller assets (e.g., small icons) can be inlined as Base64-encoded data URLs to reduce HTTP requests.
// vite.config.js
export default {
build: {
assetsInlineLimit: 4096, // Inline assets smaller than 4KB
},
};Asset Hashing
To manage caching and avoid cache conflicts, Vite adds hashes to asset filenames, ensuring that updated assets receive new filenames to force browsers to download the latest versions.
<!-- index.html -->
<img src="/static/images/logo.[hash].png" alt="Logo" />Custom Asset Handling
Customize asset handling rules using build.assetsInclude in vite.config.js to include additional asset types or modify default behavior.
// vite.config.js
export default {
build: {
assetsInclude: ['**/*.svg', '**/*.webp'], // Include SVG and WebP assets
},
};Asset Optimization
In production, Vite automatically optimizes assets, including:
- Image Compression: Use plugins or custom Rollup plugins to compress images.
- Font Optimization: Convert font formats (e.g., TTF to WOFF2) to reduce file sizes.
- Asset Merging: Combine multiple assets into a single file to reduce HTTP requests.
Deployment and CDN Integration
To further optimize asset loading, deploy assets to a CDN. Use the base configuration in vite.config.js to ensure correct asset paths for CDN referencing.
// vite.config.js
export default {
base: '/my-app/', // Specify the path if deploying to a subdirectory
};



