我最近將我的應用程式從 Rails 6 升級到 Rails 7,但有些專案似乎隨著 Stimulus 控制器從javascript/controllers.
在 Rails 6 中,我可以從目錄index.js中的檔案執行此操作javascript/controllers:
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 中匯入和注冊我的所有 Stimulus 控制器的正確方法是什么?我在檔案中找不到有關此的任何詳細資訊。
更新:
我運行了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"
uj5u.com熱心網友回復:
這取決于您當前使用的 JavaScript 捆綁器/構建器。
Stimulus 手冊解釋了在 Rails 中安裝和自動加載控制器的不同方法。
require.context只能通過 webpack 獲得。這已被 Rails 7 中的 Hotwire Stimulus 取代(以及可選的importmap)。
聽起來您目前正在使用 esbuild,因此您應該能夠index.js使用 command 更新控制器匯入rails stimulus:manifest:update。
這可能需要您rails stimulus:install先運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/459114.html
標籤:轨道上的红宝石 红宝石 网页包 ruby-on-rails-7 热线导轨
上一篇:如何讓webpack-dev-server為我的index.html服務
下一篇:我無法處理SSRReact
