我最近将我的应用程序从Rails 6升级到Rails 7,但一些项目似乎随着刺激控制器从javascript/controllers加载的方式发生了变化.

I Rails 6我可以从javascript/controllers目录中的index.js个文件中执行此操作:

const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))

但是在Rails 7中(在我的浏览器js控制台中):

Uncaught TypeError: __require.context is not a function

所以我一直在为我的每个刺激控制器打电话:

import FooBarController from "./foo_bar_controller"
application.register("foo_bar_controller", FooBarController)

在Rails 7中导入和注册所有刺激控制器的正确方法是什么?我在文件中找不到任何细节.

UPDATE:

我运行了"刺激:安装rake"任务,它确实改变了我以前不正确的一些文件.然而,现在当我构建应用程序时,我得到了以下信息:

✘ [ERROR] Could not resolve "controllers/application"
    app/javascript/controllers/index.js:3:28:
      3 │ import { application } from "controllers/application"
        ╵                             ~~~~~~~~~~~~~~~~~~~~~~~~~
  You can mark the path "controllers/application" as external to exclude it from the bundle, which will remove this error.
✘ [ERROR] Could not resolve "@hotwired/stimulus-loading"
    app/javascript/controllers/index.js:6:41:
      6 │ import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
        ╵                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  You can mark the path "@hotwired/stimulus-loading" as external to exclude it from the bundle, which will remove this error.

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

pin "application", 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"

推荐答案

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

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

require.context仅通过网页包提供.在Rails 7(以及可选的importmap)中,这已经被Hotwire+刺激所取代.

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

这可能需要你先跑rails stimulus:install.

Ruby-on-rails相关问答推荐

在 Rails 6.1 升级后,作业(job)规范使用 Minitest::UnexpectedError 包装错误

别名可能与不同模型的相同别名有许多关联?

Rails ActiveRecord 中的更新插入

Rails Scope 返回 all 而不是 nil

FactoryGirl 和 Rspec 测试中 attributes_for 的含义

简单表单关联自定义标签名称

rails 4.0, rake db:sessions:create

是否可以在 Rails 集成测试或规范中指定用户代理?

是否有与 PHP 的 isset() 等效的 Rails?

如何在 Windows 上为 Ruby 安装 sqlite3?

将根 url 重定向到 Rails 应用程序中的其他位置

Rails Activeadmin - 自定义关联 Select 框

Rails 中是否有 HTML 安全截断方法?

Rails 5:重命名表迁移

您将 Rack 中间件文件和要求放在哪里?

如何打印出范围之间的随机数?

Rspec:如何在控制器规范中分配实例变量

Rails 在 id 字段上重置种子的方法

Rails:如何在rails中使用dependent::destroy?

无法加载此类文件 -- openssl (LoadError)