Bundlers are tools that allow you to write code in a modular and easy-to-manage way, and then bundle it in a way that's optimized for production. For example, you probably want a giant front-end application to exist in your codebase as many hundreds of files, but you want to serve it to your visitors as a single file or one file per page.
The point is, a bundler takes care of transforming your code from how you're writing it to how you want it to be served. That said, popular bundlers often do a whole suite of important things, like:
For a long time, Webpack was the most popular bundler. It's still used, but Vite has been gaining a lot of traction lately. Vite is often quite a bit faster than Webpack, and it's also much easier to configure in my opinion. It's built on top of (and adds more features to) Rollup, which is another popular bundler.
Heifer's codebase has come a long way, and it's high time for a bundler. Let's install cowsay for our "moo" program, then use Vite to bundle it into a single file.
npm i cowsay
____________
< moo, there! >
------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Vite requires Node.js version 20.19.0 or higher (or 22.12.0+). Check your Node.js version with node --version. If you need to upgrade, visit nodejs.org.
npm i -D vite
import { defineConfig } from "vite";
export default defineConfig({
build: {
lib: {
entry: "main.js",
formats: ["es"],
},
},
});
build.lib - tells Vite that we’re generating a “library” bundle. In practical terms:
entry: 'main.js' - sets the entry point for the bundle as main.js.formats: ['es'] - instructs Vite to output the bundle in ES module format.By default Vite names the bundled file whatever you've named your project in package.json, but we could override this with fileName.
There are a lot of other configuration settings for Vite.
{
"scripts": {
"build": "vite build",
"start": "node dist/heifer.js"
}
}
npm run build
This should create a dist folder containing your bundled file. The bundled code might look like some Eldritch horror, but that's just bundled code for you!
You should add the dist folder to your .gitignore too. Code that can be regenerated with a command should, as a rule of thumb, be gitignored.
npm run start
If all went well, you should see a cow say moo in the terminal!
Run and submit the CLI tests.