You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7中使用Importmaps导入自定义JS文件失败求助

Rails 7 + Importmaps 自定义JS文件导入问题

正在学习Rails 7和Importmaps,跟着DHH的教程操作。教程视频已有一年历史,基于Rails 7 alpha版本,前期操作都正常,但在导入自定义JS文件时遇到问题。

问题详情

  1. 按照教程在application.js中添加代码:
import "comps/vue_components"

执行时出现JS错误:

Uncaught TypeError: Failed to resolve module specifier "comps/vue_components". Relative references must start with either "/", "./", or "../".

  1. 将代码修改为:
import "./comps/vue_components"

修改后出现静默失败——JavaScript执行完全终止,在application.js中添加console.log('hello'),只有注释掉该导入语句时才会在控制台输出内容。

相关配置文件内容

config/importmap.rb

# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", 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"

pin "trix"
pin "@rails/actiontext", to: "actiontext.js"

pin "md5", to: "https://cdn.skypack.dev/md5"

pin "vue", to: "https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.esm.browser.js"

pin_all_from "app/javascript/components", under: "comps"

application.js

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "trix"
import "@rails/actiontext"
import "./comps/vue_components"
console.log('hello')

内容的提问来源于stack exchange,提问作者Fred Willmore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:01:55