Vite JS Tutorial: Rollup for Production

beginner
11 min

Vite JS Tutorial: Rollup for Production

Welcome back to CodeYourCraft! Today, we're diving into an exciting topic: using Rollup for production with Vite JS. This powerful tool will help you optimize your JavaScript applications for real-world projects. Let's get started!

What is Rollup? 🎯

Rollup is a popular JavaScript module bundler, similar to Webpack. It takes your code, bundles it together, and optimizes it for the best performance in a production environment.

In Vite, Rollup runs behind the scenes during development, but we can use it manually for production builds.

Why use Rollup with Vite? 💡

  • Optimization: Rollup minimizes your code, compresses it, and treeshakes unused dependencies, making your application faster and more efficient.
  • TypeScript support: Rollup plays nicely with TypeScript, allowing you to write type-safe JavaScript code.
  • Easy configuration: Vite provides a simple vite.config.js file for customizing Rollup configurations.

Setting up Rollup for Production 📝

  1. First, make sure you have Vite installed. If not, you can install it using npm or yarn:
bash
npm install -g vite # or yarn global add vite
  1. Create a new Vite project:
bash
vite create my-app cd my-app
  1. To build for production, run the following command:
bash
vite build

By default, Vite will use Rollup under the hood to create an optimized production build. The output will be in the dist folder.

Customizing Rollup Configuration 📝

If you need to customize Rollup's behavior, create a vite.config.js file in the root of your project:

js
// vite.config.js import { defineConfig } from 'vite' export default defineConfig({ // Your custom Rollup configuration goes here })

Real-World Example 📝

Let's say we have a simple module, greet.js, that exports a function for greeting a person:

js
// greet.js export function greet(name) { console.log(`Hello, ${name}!`); }

To use this module in another file, say index.js, we'd import it like so:

js
// index.js import { greet } from './greet.js'; greet('John'); // Output: Hello, John!

When you run vite build, Rollup will bundle these files together and create an optimized production build.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What does Rollup do in a Vite production build?

And that's a wrap! You now have a solid understanding of using Rollup for production with Vite JS. Happy coding! 💻🎉