Rails:Stimulus: Multiple manifests

From FVue
Jump to: navigation, search

Problem

I want to have a separate Stimulus controllers for the Frontend and the Admin

Solution

Create additional tasks for the rails stimulus:admin_manifest:update and rails stimulus:frontend_manifest:update command.

# lib/tasks/stimulus_tasks.rake
require 'stimulus/manifest'
 
namespace :stimulus do
  namespace :admin_manifest do
    task :display do
      puts Stimulus::Manifest.generate_from(Rails.root.join('app/javascript/admin/controllers'))
    end
 
    task :update do
      manifest = 
        Stimulus::Manifest.generate_from(Rails.root.join('app/javascript/admin/controllers'))
 
      File.open(Rails.root.join('app/javascript/admin/controllers/index.js'), 'w+') do |index|
        index.puts '// This file is auto-generated by ./bin/rails stimulus:admin_manifest:update'
        index.puts '// Run that command whenever you add a new controller or create them with'
        index.puts '// ./bin/rails generate stimulus controllerName'
        index.puts 
        index.puts %(import { application } from "./application")
        index.puts manifest
      end
    end
  end
 
  namespace :frontend_manifest do
    task :display do
      puts Stimulus::Manifest.generate_from(Rails.root.join('app/javascript/frontend/controllers'))
    end
 
    task :update do
      manifest = 
        Stimulus::Manifest.generate_from(Rails.root.join('app/javascript/frontend/controllers'))
 
      File.open(Rails.root.join('app/javascript/frontend/controllers/index.js'), 'w+') do |index|
        index.puts '// This file is auto-generated by ./bin/rails stimulus:frontend_manifest:update'
        index.puts '// Run that command whenever you add a new controller or create them with'
        index.puts '// ./bin/rails generate stimulus controllerName'
        index.puts 
        index.puts %(import { application } from "./application")
        index.puts manifest
      end
    end
  end
end