Rails 7升级后Heroku部署SassC报错:Bootstrap未找到或无法读取
Rails 7 部署到 Heroku 时资产预编译失败(Bootstrap 导入找不到)
问题描述
将应用从 Rails 6.1 升级至 Rails 7 后,开发环境测试正常,但部署到 Heroku 时,资产预编译阶段抛出以下错误:
Running: rake assets:precompile rake aborted! SassC::SyntaxError: Error: File to import not found or unreadable: ../../../node_modules/bootstrap/scss/bootstrap. on line 7:1 of app/assets/stylesheets/application.scss >> @import "../../../node_modules/bootstrap/scss/bootstrap";
已尝试的解决方案:
- 更新并重新安装 Gem(
bundle update/bundle install) - 更新
bootstrapgem - 修改 CSS 文件中 Bootstrap 导入语句的路径
- 清理临时文件
- 更新
sassc - 升级 Yarn 并重新安装 Bootstrap(
yarn upgrade/yarn remove bootstrap && yarn add bootstrap) - 使用 npm 重新安装依赖
针对性解决方案
1. 适配 Rails 7 资产管线逻辑
Rails 7 默认采用 CSS Bundling for Rails 或 Import Maps 管理前端依赖,不再像 Rails 6 那样依赖 Sprockets 直接读取 node_modules 路径。
- 如果用 CSS Bundling 方案:
- 修改
app/assets/stylesheets/application.scss的导入语句,去掉冗长的相对路径:@import "bootstrap/scss/bootstrap"; - 在
config/initializers/assets.rb中添加node_modules到资产搜索路径:Rails.application.config.assets.paths << Rails.root.join('node_modules')
- 修改
2. 强制清除 Heroku 缓存并重新部署
Heroku 的依赖缓存可能导致 node_modules 未正确安装,执行以下命令清除缓存后重新推送代码:
heroku plugins:install heroku-repo heroku repo:purge_cache -a 你的应用名称 git push heroku main
3. 规范 Bootstrap Ruby Gem 的使用方式
如果依赖 bootstrap gem,无需手动导入 node_modules 文件,直接在 application.scss 中简化导入:
@import "bootstrap";
同时确保 Gemfile 中指定适配 Rails 7 的 Bootstrap 版本:
gem 'bootstrap', '~> 5.3'
执行 bundle install 后提交代码重新部署。
4. 检查生产环境资产配置
打开 config/environments/production.rb,确认以下配置:
config.assets.compile = false
保持默认的 false 配置,避免预编译阶段出现路径解析混乱。
5. 确认前端依赖声明完整
检查项目根目录的 package.json,确保 Bootstrap 已正确添加到依赖列表:
{ "dependencies": { "bootstrap": "^5.3.0" } }
如果缺失,执行 yarn add bootstrap,提交 package.json 和 yarn.lock 后重新部署。
内容的提问来源于stack exchange,提问作者cefsdp
相关产品推荐
相关产品推荐

