Use Bun with Vite.js and Forge

Published at Sep 16, 2023

Here's a short one. When I (re)created this blog, Bun just got tagged 1.0 and I decided to try it.

UPDATE 01/06/2024 : Since the first writing of this article, Bun has made a lot of improvements. This article has been rewritten with Bun 1.1.12.

It´s easy to use in development, just do bun run dev like if it was npm. You can also remove rm package-lock.json. I did needed to do some research for the deployment part. Let me share it with you.

Installation on Forge

So first things first, you need to install bun. The easy way is to create a new recipe and execute it. Put this command executed as forge :

Copied!
curl -fsSL https://bun.sh/install | bash

Then execute it on the desired server. You will receive a mail when it's done with console output.

Update deployment

Now update your deployment script to use bun instead of npm. For example, this Statamic website has theses lines at the end of the deployment script:

Copied!
git pull origin main
 
# ... your deployment
 
npm ci && npm run build 
bun install --frozen-lockfile && bun run build 
 
php artisan queue:restart
php please static:warm --queue
 
( flock -w 10 9 || exit 1
echo 'Restarting FPM...'; sudo -S service php reload9>/tmp/fpmlock

Here I used --frozen-lockfile to install reproducible dependencies of my dev environment, it's basically the replacement of npm ci.

You can also use --production to prevent installing dev dependencies if your package.json if it suit your needs. Read more on the documentation of the install command.

About the lockfile, it work's pretty much the same as npm with package.lock or yarn, but with bun it's a binary file called bun.lockb. Again, all the documentation here: https://bun.sh/docs/install/lockfile

Important note

You may encounter this error when deploying your project:
error: lockfile had changes, but lockfile is frozen

It happens when after you add a new package. Bun doesn't update your bun.lockb by default (see more). They recommand you to re run bun install after adding a new package.

Copied!
bun add --dev @tailwindcss/typography
bun install 

Automatic update

On Forge, composer is automatically updated. If you want automatic upgrade like composer but for bun, follow theses easy steps:

  1. Go to the Scheduler tab of your server
  2. Create a new New Scheduled Job run by forge at a nightly frequency with this command: bun upgrade

And that's it. Hope you won some milliseconds on your deployment!

If you use a CI to compile your assets. You will appreciate the time gained since lots of CI hase a time based billing.

#short #vite.js #bun #forge

Syntax highlighting provided by torchlight.dev