Ruby on Rails新手求助:如何正确安装Select2、Chosen等JS组件?
Hey there! Let's break down why you're hitting those module not found errors, and how to fix them. The core issue here is a common gotcha with Rails Webpacker: gem-installed frontend assets don't play nicely with Webpacker's module resolution—Webpacker relies on Yarn (npm) to manage its frontend dependencies, not Ruby gems. That's why easy-autocomplete worked: you installed it via Yarn, which Webpacker can directly resolve.
Step 1: Remove unnecessary gems
First, open your Gemfile and delete any lines for select2-rails or chosen-rails (if you added them). Run bundle install to clean up—we don't need these gems anymore, since we'll pull the frontend packages directly via Yarn.
Step 2: Install Select2/Chosen via Yarn
Open your terminal and run the command for the library you want:
- For Select2:
yarn add select2 - For Chosen:
yarn add chosen-js
Step 3: Correctly import assets in your pack file
Update your app/javascript/packs/application.js to properly import the JS and CSS. Here's the adjusted version for Select2 (similar logic applies to Chosen):
import Rails from "@rails/ujs" import Turbolinks from "turbolinks" import * as ActiveStorage from "@rails/activestorage" import "channels" Rails.start() Turbolinks.start() ActiveStorage.start() // Import jQuery and attach it to the window (required for Select2/Chosen) import $ from "jquery" window.jQuery = $ window.$ = $ // Import Select2 JS and CSS import "select2" import "select2/dist/css/select2.css" // ... your existing easy-autocomplete code ... document.addEventListener("turbolinks:load", function() { // Initialize Select2 $('.selector').select2(); })
Key notes here:
- We use
import(modern ES module syntax) instead ofrequire(either works, butimportis preferred now) - We explicitly attach jQuery to the global
windowobject—Select2 and Chosen expect jQuery to be globally available - For Chosen, swap the imports to:
And initialize withimport "chosen-js" import "chosen-js/chosen.css"$('.selector').chosen();
Why this works
When you install a package via Yarn, it lives in your node_modules folder—Webpacker's default lookup path for modules. The gems you used earlier placed assets in the Rails asset pipeline, which Webpacker doesn't check by default—hence the "cannot find module" error.
Troubleshooting tips
- Double-check you used the correct package name: Select2 is
select2, Chosen ischosen-js(notchosen-jquery) - If errors persist, restart your Rails server and Webpack dev server (
bin/webpack-dev-server) to clear cached module resolutions - Confirm jQuery is properly attached to the window—some libraries fail silently if jQuery isn't global
内容的提问来源于stack exchange,提问作者tkhobbes

