我正在try 与其他控制器共享刺激控制器功能,但由于assets资源 管道摘要的原因,找不到这些文件.

父级(app/javascrip/Controlders/a_Shared_Controler.js)

import {Controller} from "@hotwired/stimulus"

export default class extends Controller {
  // some shared functions
}

小孩儿

import Controller from "./a_shared_controller"

这在开发中运行良好.做这件事最好的方法是什么?

谢谢!

推荐答案

不要使用相对导入.当您像这样固定所有控制器时:

pin_all_from "app/javascript/controllers", under: "controllers"

您可以生成以下import-maps条:

<script type="importmap" data-turbo-track="reload">{
  "imports": {
    "controllers/application":      "/assets/controllers/application-368d98631bccbf2349e0d4f8269afb3fe9625118341966de054759d96ea86c7e.js",
    "controllers/hello_controller": "/assets/controllers/hello_controller-549135e8e7c683a538c3d6d517339ba470fcfb79d62f738a0a089ba41851a554.js",
    "controllers":                  "/assets/controllers/index-ed00704a3bfd9aebb7c818233ee5411c3ce8050f411b77ec27c4252ded99a59c.js",
  }
<!-- ^ this is what you can import -->
}</script>

application.js是共享文件的一个示例,它在index.js中导入:

import { application } from "controllers/application"
//                           ^
// NOTE: the name of the generated importmap is used to import

如果添加另一个文件,不要添加_controller.js,因为它会在index.js中自动加载(除非这是您想要的).


I have another answer explaining why relative paths don't work and how to maybe make them work:
https://stackoverflow.com/a/73136675/207090

Ruby-on-rails相关问答推荐

在Ruby on rails中,重复访问ActiveRecordModel返回相同的对象:预期行为还是错误?

Puma 工作人员无法在 Ubuntu 20.04 VM 上的 Rails 5.2 中启动

根据表单内的 Select 字段值渲染部分内容

Rails 7 - has_many_attached 在加载新附件时删除旧附件

NoMethodError:Puma::Events:Class 的未定义方法字符串

Ruby on Rails 有没有好的管理生成器?

有没有办法在 Rails 3.1 中检测用户代理

如何添加到序列化数组

从 Authlogic 迁移到 Devise

Rails 中页面视图的简单计数器

如何在 Rails 上生成 AuthenticityToken

在 Rails 4 中检测用户代理 - 读取 HTTP 标头

在公共 Rails 应用程序中将敏感数据存储在哪里?

Rails - 从日期和时间戳获取日期

Rails,获取模型中的资源路径

RubyMine - 关闭在空行中间单击的功能

你如何覆盖 form_for 助手中的类名?

Rails:一次添加多个 flash[:notice] 的简单方法

Rails,Docker:主机不存在:默认

ActionMailer 在开发 Rails 4 中不发送邮件