Running Rails server
In an earlier chapter, we had set up a basic Rails server. There we ran the
Rails server from the terminal using the bundle exec rails server -p 3000
command.
We can also use an alias, that is s
for server
, in the above mentioned
command to run a Rails server in the shortened format, like this:
The p
flag is used to specify the PORT
number on which the server will run.
In this case the PORT number is 3000.
Merely running the Rails server for an application that also compiles JavaScript assets can lead to performance issues and slow down the development process.
To improve efficiency, we should run the asset compilation separately.
Using Vite development server
We will run the rails server in one terminal and the
Vite server in another terminal.
Open a new terminal tab or window. In the "Terminal" app in macOS you can do so
using command + T
keys for a new tab and command + N
keys for a new terminal
window.
Once a new terminal is open, run the following command:
Because we added "dev": "vite"
to the scripts section in package.json, we can start
the Vite development server simply by running yarn dev
. When we use
yarn dev --host
, it runs the Vite server and makes it accessible over the
network, allowing other devices on that network to access the app.
Using ESBuild to compile assets
To test whether ESBuild correctly bundles our assets for production, we first need to
make the following change to the file _bundle.html.erb
:
By setting the condition to false
, we force the second conditional block to execute.
This ensures that Rails loads the precompiled assets
generated by esbuild, instead of relying on the Vite development server.
Now, we run yarn build
to trigger esbuild, which bundles our assets for production.
Once you've verified that ESBuild is set up correctly and compiles your assets, remember to change the condition back to its original state: Rails.env.development? || Rails.env.test?
.
Running the application
So to summarize, whenever testing out a Rails application in development
environment, open the Rails server in one terminal and Vite server in
another. Thus when stopping the application, you will have to exit from both
these terminals.
This setup allows the Rails server to handle backend requests while Vite manages front-end assets.
For production, ESBuild precompiles the assets, and Rails serves these files directly.
There is nothing to be committed in this chapter.