You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7升级:移除Stimulus子文件夹控制器前缀的问题及报错解决

解决Rails 7 Importmap下Stimulus子文件夹控制器无需前缀的问题

方案一:修复独立文件夹配置的报错(已移动legacy到legacy_controllers)

你之前的报错是因为缺少legacycontrollers的入口文件和对应的pin配置,按以下步骤修正:

  1. 创建legacy_controllers的入口文件
    在app/javascript/legacy_controllers下新建index.js,内容如下:
import { application } from "../controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"

// 加载legacy_controllers下的所有控制器,标识符直接使用文件名(无前缀)
eagerLoadControllersFrom("legacycontrollers", application)
  1. 更新importmap.rb配置
    添加对legacycontrollers入口的pin,确保import能找到对应文件:
pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
# 添加这两行
pin "legacycontrollers", to: "legacy_controllers/index.js", preload: true
pin_all_from "app/javascript/legacy_controllers", under: "legacycontrollers"
  1. 保持现有配置不变
    你的application.js里的import "legacycontrollers"和controllers/index.js里的eagerLoadControllersFrom("legacycontrollers", application)无需修改,报错会消失,legacy_controllers下的控制器可以直接用data-controller="sort"调用。

方案二:保留原controllers/legacy子文件夹结构

如果不想移动文件夹,可通过手动注册控制器的方式跳过自动前缀生成:

  1. 修改app/javascript/controllers/index.js
    替换原有的自动加载逻辑,添加对legacy文件夹控制器的手动注册:
import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"

// 加载根目录下的控制器(保留原有逻辑)
eagerLoadControllersFrom("controllers", application)

// 手动加载legacy子文件夹的控制器,自定义标识符(去掉legacy前缀)
const loadLegacyControllers = async () => {
  // 匹配legacy下所有_controller.js文件
  const legacyModules = import.meta.glob("./legacy/*_controller.js")
  for (const filePath in legacyModules) {
    const module = await legacyModules[filePath]()
    // 从文件名提取控制器标识符(比如sort_controller.js → sort)
    const identifier = filePath.split("/").pop().replace("_controller.js", "")
    // 注册控制器,使用自定义标识符
    application.register(identifier, module.default)
  }
}

loadLegacyControllers()
  1. 无需修改其他配置
    保持config/importmap.rb、application.js的原有配置即可,此时controllers/legacy/sort_controller.js可以直接通过data-controller="sort"调用,无需添加legacy--前缀。

内容的提问来源于stack exchange,提问作者Sig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 14:55:07