3

我不确定这是 importmaps 问题还是其他问题,但在 Rails 7.0.0.alpha2 中,我在 javascript 文件上遇到 404 错误。

在此处输入图像描述

想知道我是否缺少某种生产“编译”步骤,因为它在开发中运行良好。

# app/javascript/application.js
import "@hotwired/turbo-rails"
import "controllers"


# app/javascript/controllers/index.js
import { application } from "./application"

import VoteController from "./vote_controller.js"
application.register("vote", VoteController)


# app/javascript/controllers/vote_controller.js
import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="vote"
export default class extends Controller {
  static targets = ["element"];

  toggle(event) {
    //event.preventDefault();
    event.target.classList.add("opacity-100");
    event.target.classList.remove("opacity-0");
  }
}


# config/importmap.rb
pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.js"
pin "@hotwired/stimulus", to: "stimulus.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin_all_from "app/javascript/controllers", under: "controllers"

然后在我的app/views/layouts/application.html.erb文件中,我<%= javascript_importmap_tags %>用来包含所有内容。

如果我设置config.assets.compile = trueproduction.rb错误就会消失......但我不确定为什么或是否解决了核心问题。

4

2 回答 2

0

Rails 7.0.0app/javascript/controllers/index.js已修改。我找到了几种不同的方法来解决这个问题。

首先尝试将您的import { application }行更改为 import from controllers/application,如下所示:

import { application } from "controllers/application"

然后修改每个特定控制器导入的from参数,如下所示"controllers/name_controller"


可选:

删除每个控制器的单独导入并使用:

// Eager load all controllers defined in the import map under controllers/**/*_controller
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)

或这个:

// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!)
import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"
lazyLoadControllersFrom("controllers", application)

这似乎已经为我解决了。奇怪的是,该rails stimulus:manifest:update命令将用不起作用的旧样式替换它。

有关根本原因的更多信息和讨论: https ://github.com/hotwired/stimulus-rails/issues/87

于 2021-12-16T18:22:32.003 回答
0

如果您使用的是Rails 7.0.0+(稳定版),则不再需要运行rails stimulus:manifest:update(使用import maps时)也不需要单独导入每个控制器。

因此,将您的所有内容替换app/javascript/controllers/index.js为以下内容:

// Import and register all your controllers from the importmap under controllers/*

import { application } from "controllers/application"

// Eager load all controllers defined in the import map under controllers/**/*_controller
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)

// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!)
// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"
// lazyLoadControllersFrom("controllers", application)

上面的代码是从https://github.com/hotwired/stimulus-rails/blob/main/lib/install/app/javascript/controllers/index_for_importmap.js复制的。

于 2021-12-29T06:00:41.510 回答