Vite is a tool that helps bundle JavaScript files through native ES modules. Vite builds files much faster compared to traditional bundlers like Webpacker by leveraging native ES module. We use Vite for development to take advantage of its fast hot module replacement.
esbuild is another modern JavaScript bundler written in Go that we use for production builds.
Together, they provide a more efficient alternative to webpack-based solutions like Shakapacker, with significantly faster build times.
Setting up Vite and ESBuild
First, we need to add Vite to our project.
Now, let's create the configuration files for Vite and ESBuild by importing them
from wheel by running the commands below:
These configuration files provide the basic setup for Vite and ESBuild and can be used to customize
their default behavior.
Let's also add some common configuration files which both our Vite and ESBuild configs rely on.
Add this to the config.js
file created:
Run the command below to copy the build-specific constants into the config/build/constants.js
file.
Now, let's move the file app/javascript/application.js
to app/javascript/packs/application.js
as per the configuration files we just created.
While creating the granite project, the scripts
section in package.json
came with
some default CLI options for ESBuild. However, since now we have esbuild.config.js
file to
manage the build process, we no longer need those default CLI options. Instead, we will update the
scripts to use node esbuild.config.js
, ensuring that our custom configuration is used for
building assets when running the yarn build
command.
Let's also add "dev": "vite"
to the scripts section to make it easy to
start the Vite development server with yarn dev
command.
Replace the value of scripts
key in package.json with the following:
Next, let's add .browserlistrc
file to the application.
The browserslist configuration controls the outputted JavaScript so that the emitted code
will be compatible with the browsers specified. cover 95%
selects the smallest set of popular
browser versions with collective usage over 95% of the audience worldwide.
Let's now install the below packages to our project as a part of the configuration files:
Manage Asset Loading for Development and Production
Next, we need to handle whether to pull assets from the Vite dev server in development or load them from precompiled assets in production, since we will be using Vite for development and ESBuild for production. We create a _bundle.html.erb
partial to manage this dynamically. We will render this partial in application.html.erb
, which will ensure that the correct assets get loaded without cluttering application.html.erb
.
Run the commands below to create the bundle partial:
Now, let's render the bundle partial in application.html.erb
:
Once verified, add this new application to git: