Rails 7:加载所有 Stimulus 控制器

JP *_*shy 6 ruby ruby-on-rails webpack hotwire-rails ruby-on-rails-7

我最近将我的应用程序从 Rails 6 升级到 Rails 7,但有些项目似乎随着 Stimulus 控制器从javascript/controllers.

\n

在 Rails 6 中,我可以从index.js以下文件中执行此操作javascript/controllers directory:

\n
const context = require.context("controllers", true, /_controller\\.js$/)\napplication.load(definitionsFromContext(context))\n
Run Code Online (Sandbox Code Playgroud)\n

然而在 Rails 7 中,这会引发(在我的浏览器 js 控制台中):

\n
Uncaught TypeError: __require.context is not a function\n
Run Code Online (Sandbox Code Playgroud)\n

所以我不得不为我的每个刺激控制器调用这个:

\n
import FooBarController from "./foo_bar_controller"\napplication.register("foo_bar_controller", FooBarController)\n
Run Code Online (Sandbox Code Playgroud)\n

在 Rails 7 中导入和注册所有 Stimulus 控制器的正确方法是什么?我在文档中找不到有关此内容的任何详细信息。

\n

更新:

\n

我运行了stimulus:install rake 任务,它确实更改了我之前不正确的一些文件。然而现在当我构建应用程序时我得到了这个:

\n
\xe2\x9c\x98 [ERROR] Could not resolve "controllers/application"\n    app/javascript/controllers/index.js:3:28:\n      3 \xe2\x94\x82 import { application } from "controllers/application"\n        \xe2\x95\xb5                             ~~~~~~~~~~~~~~~~~~~~~~~~~\n  You can mark the path "controllers/application" as external to exclude it from the bundle, which will remove this error.\n\xe2\x9c\x98 [ERROR] Could not resolve "@hotwired/stimulus-loading"\n    app/javascript/controllers/index.js:6:41:\n      6 \xe2\x94\x82 import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"\n        \xe2\x95\xb5                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  You can mark the path "@hotwired/stimulus-loading" as external to exclude it from the bundle, which will remove this error.\n
Run Code Online (Sandbox Code Playgroud)\n

这也是我的 importmap.rb 文件中的内容:

\n
pin "application", preload: true\npin "@hotwired/stimulus", to: "stimulus.min.js", preload: true\npin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true\npin_all_from "app/javascript/controllers", under: "controllers"\n
Run Code Online (Sandbox Code Playgroud)\n

Ton*_*rra 11

这取决于您当前使用的 JavaScript 捆绑器/构建器。

Stimulus Handbook解释了在 Rails 中安装和自动加载控制器的不同方法。

require.context只能通过 webpack 获得。这已被 Rails 7 中的 Hotwire+Stimulus 取代(以及可选的importmap)。

听起来您当前正在使用 esbuild,因此您应该能够index.js使用命令更新控制器导入rails stimulus:manifest:update

这可能需要您rails stimulus:install先运行。