如何解决「Error: Unable to resolve specifier 'stimulus'」报错
解决无法解析specifier 'stimulus'的问题
问题根源
- 控制器导入路径错误:
test-controller.js中使用了import { Controller } from "stimulus",但当前Stimulus属于Hotwired生态,官方包名已更新为@hotwired/stimulus,旧的stimulus标识符无对应模块映射。 - Import Map配置异常:浏览器无法找到
stimulus对应的模块文件,因为项目的import map未配置该标识符的映射规则。
解决步骤
1. 修正控制器导入语句
打开app/javascript/controllers/test-controller.js,将首行代码修改为:
import { Controller } from "@hotwired/stimulus"
2. 验证并修复Import Map配置
检查项目根目录下的config/importmap.rb文件,确保包含以下配置:
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
若缺少上述配置,添加后运行bin/importmap install更新映射,再重启服务器。
3. 清除缓存并重启服务
- 强制刷新浏览器(Ctrl+Shift+R / Cmd+Shift+R),清除旧缓存文件
- 重启项目服务器,确保新配置生效
内容的提问来源于stack exchange,提问作者Jerome
相关产品推荐
相关产品推荐

