gpt4 book ai didi

ruby-on-rails - rails 7 : Loading all Stimulus controllers

转载 作者:行者123 更新时间:2023-12-02 15:53:14 35 4
gpt4 key购买 nike

我最近将我的应用程序从 Rails 6 升级到 Rails 7,但是一些项目似乎随着从 javascript/controllers 加载 Stimulus Controller 的方式发生了变化。

在 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

所以我一直在为我的每个 Stimulus Controller 调用它:

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

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

更新:

我运行了 stimulus:install 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 中安装和自动加载 Controller 的不同方法。

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

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

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

关于ruby-on-rails - rails 7 : Loading all Stimulus controllers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71898315/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com