Welcome to the Vite JS tutorial where we'll dive into the world of modern front-end development! Today, we'll explore Manual Chunks Configuration.
Chunks are subdivisions of a JavaScript bundle that Vite creates during the build process. They help optimize the loading process, making your application faster.
Manual chunks configuration allows you to control how your application's code is divided into chunks. This can significantly improve the loading performance of your application.
First, let's set up a new Vite project:
npm create vite my-app
cd my-appNow, open the vite.config.js file in your project root:
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
// ... (existing config)
build: {
rollupOptions: {
output: {
// This is where we'll configure chunks
}
}
}
})Vite uses Rollup under the hood, and to configure chunks, we'll use Rollup's chunkSize and esbuildMinify options.
The chunkSize option lets you define the size (in bytes) above which a module will be moved into its own chunk. For example:
// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
output: {
chunkSize: 50000, // Each chunk will not exceed 50,000 bytes
}
}
}
})The esbuildMinify option allows you to control how your code is minified, and you can use it to create minified chunks:
// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
output: {
chunkSize: 50000,
esbuildMinify: true, // Enable minification
// You can also customize minification options here
}
}
}
})Let's create a simple example to see how manual chunks configuration works. Create a new file called big-module.js:
// big-module.js
function bigFunction() {
// Implementation of a large function
}
export default bigFunctionNow, import this module in your main.js file and create a simple component:
// main.js
import bigFunction from './big-module.js'
function MyComponent() {
bigFunction()
// ... (component implementation)
}
export default MyComponentFinally, update your vite.config.js file to split the code into two chunks:
// vite.config.js
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
build: {
rollupOptions: {
output: {
chunkSize: 20000, // Each chunk will not exceed 20,000 bytes
esbuildMinify: true,
}
},
plugins: [
createHtmlPlugin({
minify: true,
inject: {
data: {
title: 'My Component',
},
},
}),
],
},
})Run your Vite development server:
npm run devNow, if you inspect your application's source code, you'll see that the big module has been split into two chunks:
main.js (contains MyComponent)big-module.js (contains the big function)What is the purpose of the `chunkSize` option in Vite's manual chunks configuration?