The evolution of front-end tooling has significantly enhanced the developer experience. Vite, known for its lightning-fast build tool and hot module replacement, now integrates seamlessly with Ruby on Rails via the vite_rails
gem. Gone are the days of slow webpack builds โ with Vite, you get instant feedback and blazing-fast development cycles.
In this comprehensive guide, we'll walk through setting up a modern Rails application with React using Vite, creating a powerful full-stack development environment.
Prerequisites
Before we begin, ensure you have the following installed:
- Ruby (3.0+)
- Rails (7.0+)
- Node.js (16+)
- npm or yarn
Step 1: Create a New Rails Application
First, let's create a fresh Rails project:
rails new rails_react_app --skip-javascript
cd rails_react_app
Note: We use
--skip-javascript
to avoid conflicts with Rails' default JavaScript setup since we'll be using Vite.
Step 2: Add Vite Rails
Add the vite_rails
gem to your Gemfile:
# Gemfile
gem 'vite_rails'
Install the gem and set up Vite:
bundle install
bundle exec vite install
This command will:
- Generate
package.json
with Vite dependencies - Create
vite.config.ts
configuration file - Set up the
app/frontend/entrypoints/
directory (default location for JS entrypoints) - Configure Rails to work with Vite
For more details, check the official guide: vite-ruby.netlify.app/guide/
Step 3: Install React Dependencies
Install React and its dependencies using npm:
npm install react react-dom @vitejs/plugin-react
Update your vite.config.ts
to include the React plugin:
// vite.config.ts
import { defineConfig } from 'vite'
import RubyPlugin from 'vite-plugin-ruby'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
RubyPlugin(),
react(),
],
})
Step 4: Create Your React Application Structure
Let's organize our code properly. Create the necessary directories and files:
mkdir -p app/frontend/src/components
touch app/frontend/entrypoints/application.jsx
Create the main React component:
// app/frontend/src/App.jsx
import React from 'react';
const App = () => {
return (
<div className="container mx-auto p-8">
<h1 className="text-4xl font-bold text-blue-600">
Hello from Rails + React + Vite! ๐
</h1>
<p className="mt-4 text-gray-600">
Your modern full-stack development environment is ready!
</p>
</div>
);
};
export default App;
Create a sample component:
// app/frontend/src/components/Welcome.jsx
import React from 'react';
const Welcome = ({ message }) => {
return (
<div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
<p>{message}</p>
</div>
);
};
export default Welcome;
Step 5: Set Up Your Application Entrypoint
Update your entrypoint file to render the React app:
// app/frontend/entrypoints/application.jsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from '../src/App';
// Import CSS if you're using any
import './application.css';
document.addEventListener('DOMContentLoaded', () => {
const rootElement = document.getElementById('root');
if (rootElement) {
const root = createRoot(rootElement);
root.render(<App />);
}
});
Step 6: Update Your Rails Layout
Modify your application layout to include Vite assets and provide a mount point for React:
<!-- app/views/layouts/application.html.erb -->
<!DOCTYPE html>
<html>
<head>
<title>Rails React App</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= vite_client_tag %>
<%= vite_stylesheet_tag 'application' %>
</head>
<body>
<div id="root"></div>
<%= yield %>
<%= vite_javascript_tag 'application' %>
</body>
</html>
Step 7: Create a Controller and Route
Generate a controller to serve your React app:
rails generate controller Pages index
Update the controller:
# app/controllers/pages_controller.rb
class PagesController < ApplicationController
def index
# This will render the view where React will mount
end
end
Set up your routes:
# config/routes.rb
Rails.application.routes.draw do
root 'pages#index'
get 'pages/index'
end
Create the view (it can be minimal since React handles the UI):
<!-- app/views/pages/index.html.erb -->
<!-- React will mount here via the #root div in the layout -->
Step 8: Start Your Development Servers
Now you can start both Rails and Vite in development mode:
Terminal 1 - Rails server:
rails server
Terminal 2 - Vite dev server:
bin/vite dev
Alternatively, you can use a process manager like foreman
. Create a Procfile.dev
:
web: rails server -p 3000
vite: bin/vite dev
Then run:
foreman start -f Procfile.dev
Key Benefits of This Setup
- โก Lightning Fast: Vite's hot module replacement provides instant feedback
- ๐ง Modern Tooling: ES modules, TypeScript support out of the box
- ๐ฆ Optimized Builds: Vite creates highly optimized production bundles
- ๐ฏ Rails Integration: Seamless integration with Rails asset pipeline
- ๐ ๏ธ Developer Experience: Excellent debugging and development tools
Production Deployment
For production deployment, Vite will automatically build optimized assets. Make sure to:
- Add the build step to your deployment process:
bundle exec vite build
- Ensure your production environment serves static assets properly
Troubleshooting Common Issues
Issue: React not mounting
- Ensure the
#root
div exists in your layout - Check browser console for JavaScript errors
- Verify Vite dev server is running
Issue: Assets not loading
- Confirm
vite_client_tag
andvite_javascript_tag
are in your layout - Check that Vite configuration is correct
- Ensure all dependencies are installed
Issue: Hot reload not working
- Restart the Vite dev server
- Check for syntax errors in your React components
- Verify your Vite configuration includes the React plugin
Conclusion
You now have a powerful, modern Rails application with React and Vite! This setup provides:
- Instant hot module replacement for rapid development
- Optimized production builds
- Modern JavaScript tooling
- Seamless Rails integration
The combination of Rails' robust backend capabilities with React's dynamic frontend and Vite's exceptional developer experience creates an ideal environment for building modern web applications.
Happy coding! ๐
For more advanced configurations and deployment strategies, check out the Vite Ruby documentation and React documentation.
Top comments (0)