首页 > 解决方案 > 在生产环境中使用 Rails 7 中的 importmaps 时出现 404 错误

问题描述

我不确定这是 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错误就会消失......但我不确定为什么或是否解决了核心问题。

标签: ruby-on-railsimport-mapsruby-on-rails-7

解决方案


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


推荐阅读