ruby-on-railsruby-on-rails-7stimulusjs

How to disable stimulus:manifest:update when generating a stimulus controller


On Rails 7, when I run rails generate stimulus controller_name, rails stimulus:manifest:update is automatically triggered. Is there any way to disable this hook ?


Solution

  • This is not optional (unless you have importmap.rb):
    https://github.com/hotwired/stimulus-rails/blob/v1.2.1/lib/generators/stimulus/stimulus_generator.rb#L9

    Two solutions:


    Make a generator

    You could make your own generator and use it instead of bin/rails g stimulus:

    $ rails g generator stimulus/controller
    
    # lib/generators/stimulus/controller_generator.rb
    
    require "generators/stimulus/stimulus_generator"
    
    class Stimulus::ControllerGenerator < StimulusGenerator
      # +++
      source_root superclass.source_root
    
      # -m to update manifest, otherwise no update
      class_option :manifest, type: :boolean, default: false, aliases: "-m"
      # -M to skip manifest, otherwise update
      # class_option :skip_manifest, type: :boolean, default: false, aliases: "-M"
      # ###
    
      def copy_view_files
        @attribute = stimulus_attribute_value(controller_name)
        template "controller.js", "app/javascript/controllers/#{controller_name}_controller.js"
    
        # +++
        return if !options[:manifest]         # no update by default
        # return if options[:skip_manifest]   # update by default
        # ###
    
        rails_command "stimulus:manifest:update" unless Rails.root.join("config/importmap.rb").exist?
      end
    end
    
    $ bin/rails g stimulus:controller test
          create  app/javascript/controllers/test_controller.js
    
    $ bin/rails g stimulus:controller test -m
       identical  app/javascript/controllers/test_controller.js
           rails  stimulus:manifest:update
    

    Skip "stimulus:manifest:update" task

    This is a simpler option to make the default bin/rails g stimulus skip the update:

    # lib/tasks/skip_stimulus_manifest.rake
    
    Rake::Task["stimulus:manifest:update"].clear
    
    namespace :stimulus do
      namespace :manifest do
        task :update do
          puts "Skipping manifest update"
        end
      end
    end
    
    $ bin/rails g stimulus test
       identical  app/javascript/controllers/test_controller.js
           rails  stimulus:manifest:update
    Skipping manifest update