ViewComponent Controller w/ Stimulus

Install view component and setup requirements to work with stimulus.
Icons/chart bar
Used 58 times
Created by
M Maksim Vakarchuk

Usage
Follows this thread to setup stimulus with view components

// Register controllers manually with example from app/components/named_component_controller.js:
import NamedComponentController from 'named_component_controller';
application.register(
  'named-component',
  NamedComponentController
);

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/X6ksy1"
Template Source

Review the code before running this template on your machine.

say "Configuring Stimulus controllers inside of ViewComponents"

say "Updating config/importmap.rb"
append_to_file "config/importmap.rb" do
  'pin_all_from "app/components"'
end

say "Updating config/initializers/assets.rb"
append_to_file "config/initializers/assets.rb" do
  "Rails.application.config.assets.paths << 'app/components'\nRails.application.config.assets.debug = true"
end

say "Updating config/environments/development.rb"
insert_into_file "config/environments/development.rb", before: "\nend" do
  "\n  config.assets.check_precompiled_asset = false"
end

say "Updating app/assets/config/manifest.js"
append_to_file "app/assets/config/manifest.js" do
  '//= link_tree ../../components .js'
end

say "Adding example javascript/controllers/index.js"
append_to_file "app/javascript/controllers/index.js" do
  "\n// Register controllers manually with example from app/components/named_component_controller.js:\n// import NamedComponentController from 'named_component_controller';\n// application.register(\n//   'named-component',\n//   NamedComponentController\n// );"
end

say "Done! Remember to initialize your components with --stimulus. Example: bin/rails generate component TestComponent --stimulus"
Comments

Sign up or Login to leave a comment.