How to Use Webpacker in Rails: Setup and Usage Guide
In Rails,
Webpacker is used to manage JavaScript, CSS, and other assets with modern tools like Webpack. You install it by adding the gem, running rails webpacker:install, and then place your JavaScript files in app/javascript/packs. You include packs in views using javascript_pack_tag.Syntax
Webpacker integrates Webpack with Rails to compile and bundle assets. Key parts include:
rails webpacker:install: Sets up Webpacker in your Rails app.app/javascript/packs/application.js: Entry point for JavaScript.javascript_pack_tag 'application': Helper to include compiled JavaScript in views.
bash and erb
bundle add webpacker
rails webpacker:install
# In your Rails view (e.g., app/views/layouts/application.html.erb):
<%= javascript_pack_tag 'application' %>Example
This example shows how to set up Webpacker, add a simple JavaScript alert, and include it in a Rails view.
bash, javascript, erb
# 1. Add Webpacker gem and install bundle add webpacker rails webpacker:install # 2. Create a JavaScript pack file at app/javascript/packs/application.js // app/javascript/packs/application.js alert('Hello from Webpacker!'); # 3. Include the pack in your layout (app/views/layouts/application.html.erb) <!DOCTYPE html> <html lang="en"> <head> <title>Webpacker Demo</title> <%= javascript_pack_tag 'application' %> </head> <body> <h1>Welcome to Rails with Webpacker</h1> </body> </html>
Output
When you load the page in a browser, an alert box pops up with the message: "Hello from Webpacker!"
Common Pitfalls
Common mistakes when using Webpacker include:
- Not running
rails webpacker:installafter adding the gem. - Placing JavaScript files outside
app/javascript/packsand not importing them properly. - Forgetting to include
javascript_pack_tagin views, so scripts don’t load. - Not restarting the Rails server after installing Webpacker.
Always check your browser console for errors if scripts don’t run.
javascript
# Wrong: Placing JS file outside packs and not importing # app/javascript/hello.js console.log('Hello'); # Right: Import it in a pack // app/javascript/packs/application.js import '../hello'; console.log('Pack loaded');
Quick Reference
| Command / Usage | Description |
|---|---|
| bundle add webpacker | Add Webpacker gem to your Rails app |
| rails webpacker:install | Install Webpacker and set up config files |
| app/javascript/packs/application.js | Main JavaScript entry point |
| javascript_pack_tag 'application' | Include compiled JS pack in views |
| bin/webpack-dev-server | Run Webpack dev server for live reload |
Key Takeaways
Run 'rails webpacker:install' after adding the Webpacker gem to set up your app.
Place JavaScript files inside 'app/javascript/packs' or import them there.
Use 'javascript_pack_tag' in your views to load compiled JavaScript.
Restart your Rails server after installing or changing Webpacker setup.
Check browser console for errors if your JavaScript does not run.