Rails 6:如何通过Webpacker添加jQuery-UI以实现日期选择器?
Hey there! Let's break this down for you—since you're struggling with integrating jquery-ui-rails via Webpacker, here are a couple of solid paths forward:
Option 1: Skip Webpacker and use jquery-ui-rails with the asset pipeline
If you don't strictly need to use Webpacker for this, the asset pipeline is the documented, straightforward way to use this gem:
- Add the gem to your
Gemfile:gem 'jquery-ui-rails' - Run
bundle installto install it. - In
app/assets/javascripts/application.js, add only the datepicker component (no need to load the entire jQuery UI library)://= require jquery-ui/datepicker - In
app/assets/stylesheets/application.css, add the corresponding styles:*= require jquery-ui/datepicker - Finally, initialize the datepicker in your view (adjust for Turbolinks if you're using it):
// With Turbolinks $(document).on('turbolinks:load', function() { $('#your-date-field-id').datepicker(); }); // Without Turbolinks $(document).ready(function() { $('#your-date-field-id').datepicker(); });
Option 2: Use Webpacker with npm (instead of the gem)
If you want to stick with Webpacker, you can avoid the gem entirely and install jQuery UI via yarn:
- Install the required packages:
yarn add jquery jquery-ui - In
app/javascript/packs/application.js, import jQuery, expose it to the global scope, then import the datepicker widget and its styles:import $ from 'jquery'; window.$ = $; // Expose jQuery to global scope for the datepicker import 'jquery-ui/ui/widgets/datepicker'; import 'jquery-ui/themes/base/datepicker.css'; - Then initialize it the same way as shown in Option 1.
Option 3: Switch to a modern, Rails-friendly alternative gem
If you're open to ditching jQuery UI entirely, there are lighter, more modern datepickers that play better with modern Rails setups:
flatpickr-rails: A lightweight, dependency-free (no jQuery needed) datepicker with great mobile support.
- Add to
Gemfile:gem 'flatpickr-rails' - Import in
application.js://= require flatpickr - Import in
application.css://= require flatpickr - Initialize:
flatpickr('#your-date-field-id');
- Add to
rails-bootstrap-datepicker: Perfect if you're using Bootstrap in your app—matches Bootstrap's styling and works with jQuery.
- Add to
Gemfile:gem 'rails-bootstrap-datepicker' - Follow the gem's docs to import the JS/CSS, then initialize like you would jQuery UI's datepicker.
- Add to
stimulus-datepicker: Built for Rails' default Stimulus framework, no jQuery required. It's a native Stimulus controller that integrates seamlessly with modern Rails apps.
- Add to
Gemfile:gem 'stimulus-datepicker' - Generate the controller and bind it to your input using Stimulus'
data-controllerattribute.
- Add to
内容的提问来源于stack exchange,提问作者arnasklas

