stimulus-rails

repository·main·Indexed 20 days ago

https://github.com/hotwired/stimulus-rails

A Rails integration for the Stimulus JavaScript framework. It supports both modern Import Maps and traditional JavaScript bundlers, providing tools for automatic controller registration, manifest updates via `bin/rails stimulus:manifest:update`, and a generator for creating new Stimulus controllers.

Tokens
2.7K
Snippets
9
Records
10
Agent score
71%

What's inside stimulus-rails

  1. Eager vs Lazy loading controllers with Import Maps

    main

    In an import-mapped application, you can control how controllers are loaded in app/javascript/controllers/index.js:

    • Eager Loading: Uses eagerLoadControllersFrom. All controllers are loaded when the application starts. This is suitable for a modest number of controllers.
    • Lazy Loading: Uses lazyLoadControllersFrom. Controllers are only loaded when their data-controller identifier is encountered in the DOM. This is recommended if your application has a large number of controllers.
    // app/javascript/controllers/index.js
    import { application } from "controllers/application"
    
    // For Eager Loading:
    import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
    eagerLoadControllersFrom("controllers", application)
    
    // For Lazy Loading:
    import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"
    lazyLoadControllersFrom("controllers", application)
  2. Generate and update Stimulus controllers with Bundlers

    main

    When using a JavaScript bundler, you must keep app/javascript/controllers/index.js in sync with your controller files. You can do this in two ways:

    1. Using the Generator: Run ./bin/rails generate stimulus [controller_name]. This creates the controller file and automatically updates the manifest (index.js).
    2. Using the Manifest Task: Run ./bin/rails stimulus:manifest:update. This updates the index.js file to include all existing controllers.
    # Create a new controller and update the manifest automatically
    ./bin/rails generate stimulus hello
    
    # Or just update the manifest manually
    ./bin/rails stimulus:manifest:update
  3. Install stimulus-rails manually with Import Maps

    main

    If the installer fails or you prefer manual configuration for an import-mapped application, follow these steps:

    1. Add gem 'stimulus-rails' to your Gemfile and run bundle install.
    2. Create app/javascript/controllers/application.js to initialize the Stimulus application.
    3. Create app/javascript/controllers/index.js to load your controllers using @hotwired/stimulus-loading.
    4. Import the controllers in your main app/javascript/application.js.
    5. Pin the necessary dependencies in config/importmap.rb.
    // app/javascript/controllers/application.js
    import { Application } from "@hotwired/stimulus"
    
    const application = Application.start()
    
    // Configure Stimulus development experience
    application.debug = false
    window.Stimulus   = application
    
    export { application }
    // app/javascript/controllers/index.js
    import { application } from "controllers/application"
    
    // Eager load all controllers defined in the import map under controllers/**/*_controller
    import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
    eagerLoadControllersFrom("controllers", application)
    // app/javascript/application.js
    import "controllers"
    # config/importmap.rb
    pin "@hotwired/stimulus", to: "stimulus.min.js"
    pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
    pin_all_from "app/javascript/controllers", under: "controllers"
  4. Install stimulus-rails using the installer

    main

    For Rails 6 applications, the easiest way to install stimulus-rails is using the provided installer. This will automatically detect if you are using importmap-rails or a JavaScript bundler (like jsbundling-rails) and configure your files accordingly.

    1. Add the gem to your Gemfile.
    2. Install the gem.
    3. Run the stimulus installation task.
    # Gemfile
    gem 'stimulus-rails'
    ./bin/bundle install
    ./bin/rails stimulus:install
  5. Install stimulus-rails manually with a JavaScript Bundler

    main

    For applications using a Node-capable bundler (e.g., via jsbundling-rails), follow these steps:

    1. Add gem 'stimulus-rails' to your Gemfile and run bundle install.
    2. Create app/javascript/controllers/application.js to initialize the Stimulus application.
    3. Create app/javascript/controllers/index.js to import and register your controllers.
    4. Import the controllers in your main app/javascript/application.js.
    5. Add the @hotwired/stimulus package to your package.json via yarn.
    // app/javascript/controllers/application.js
    import { Application } from "@hotwired/stimulus"
    
    const application = Application.start()
    
    // Configure Stimulus development experience
    application.debug = false
    window.Stimulus   = application
    
    export { application }
    // app/javascript/controllers/index.js
    // This file is auto-generated by ./bin/rails stimulus:manifest:update
    import { application } from "./application"
    
    // Manual registration example:
    // import HelloController from "./hello_controller"
    // application.register("hello", HelloController)
    // app/javascript/application.js
    import "./controllers"
    yarn add @hotwired/stimulus
  6. How Stimulus controller registration works

    main

    The stimulus-rails gem automates the registration of JavaScript controllers with your Stimulus application. It scans your controllers directory for files ending in _controller (e.g., hello_controller.js or nested/folder/hello_controller.js) and generates an index.js file that imports and registers them.

    Naming Conventions:

    • JavaScript Class Name: The file path is converted to a CamelCase class name. For example, nested/folder/hello_controller.js becomes Nested::Folder::Hello (or Nested__Folder__Hello in the generated JS import).
    • HTML Identifier (Tag Name): The file path is converted to a kebab-case string used in data-controller attributes. For example, nested/folder/hello_controller.js becomes nested--folder--hello.
  7. Create a Stimulus controller

    main

    A Stimulus controller is a JavaScript class that extends Controller from @hotwired/stimulus. It connects to HTML elements via the data-controller attribute. You can define static targets to easily interact with specific elements within the controller's scope.

    // app/javascript/controllers/hello_controller.js
    import { Controller } from "@hotwired/stimulus"
    
    // Connects with data-controller="hello"
    export default class extends Controller {
      static targets = [ "name", "output" ]
    
      greet() {
        this.outputTarget.textContent = `Hello, ${this.nameTarget.value}!`
      }
    }
  8. Prevent Stimulus assets from precompiling

    main

    If you are using a JavaScript bundler (like jsbundling-rails) and do not want the stimulus-rails gem to automatically add its internal assets to your Sprockets/Propshaft precompilation list, you can remove them in a Rails initializer.

    Use the Stimulus::Engine::PRECOMPILE_ASSETS constant to identify the files being added.

    # config/initializers/stimulus_assets.rb
    Rails.application.configure do
      config.after_initialize do
        config.assets.precompile -= Stimulus::Engine::PRECOMPILE_ASSETS
      end
    end
  9. Generate a new Stimulus controller

    main

    Use the Stimulus Rails generator to create a new Stimulus controller file in app/javascript/controllers/. The generator automatically handles naming conventions and, by default, updates the Stimulus manifest to ensure the new controller is discoverable.

    To prevent the generator from updating the Stimulus manifest (for example, if you are managing imports manually), use the --skip-manifest flag.

    # Standard usage (updates manifest)
    rails generate stimulus <name>
    
    # Usage without updating the manifest
    rails generate stimulus <name> --skip-manifest
  10. Update the Stimulus manifest via CLI

    main

    To register new Stimulus controllers in your application, you must update the auto-generated index.js file. This is done by running the following command in your terminal:

    bin/rails stimulus:manifest:update

    You should run this command whenever you:

    1. Add a new controller file manually.
    2. Create a new controller using the generator: ./bin/rails generate stimulus controllerName.
    # Run this command to sync your JavaScript index file with your new controllers
    ./bin/rails stimulus:manifest:update