如何在Rails中使用animate.css?animate-rails在Heroku上无法生效
问题根因
你当前同时引入了两套冲突的animate.css资源,生产环境资产预编译逻辑和类名规则不匹配:
- Gemfile安装的
animate-rails对应旧版animate.css,使用无animate__前缀的类名规则,通过Sprockets资产管道加载 - package.json安装的
animate.css@4.1.1是新版,要求所有动画类名带animate__前缀,通过Webpacker加载
两套资源在生产环境预编译时出现优先级冲突,旧版样式覆盖了新版规则,导致你写的带前缀类名无对应样式生效。
修复方案(推荐适配Rails 6+默认的Webpacker管理逻辑)
- 移除冗余的gem依赖:
- 删掉Gemfile中的
gem "animate-rails"行 - 本地执行
bundle install更新Gemfile.lock
- 删掉Gemfile中的
- 修正样式引入配置:
- 删掉application.css.scss中的
*= require animate行,npm引入的样式不需要通过Sprockets声明 - 确认application.js中的
import 'animate.css/animate'保留
- 删掉application.css.scss中的
- 修正HTML类名错误:你当前写的
fadeIn类名缺少新版要求的前缀,修改为:.nav-item.animate__animated.animate__fadeIn.animate__slower.animate__delay-2s Sample Text - 确认生产环境资产编译逻辑:
- 部署前本地执行
RAILS_ENV=production rails assets:precompile,将编译后的public/assets、public/packs目录下的变更提交到代码仓库后再推送到Heroku - 若不想本地预编译,可将production.rb中的
config.assets.compile临时改为true,确认生效后再根据需求调整预编译策略
- 部署前本地执行
备选方案(沿用gem版本)
如果要继续使用animate-rails gem,做以下调整即可:
- 删掉package.json中的
"animate.css": "^4.1.1"依赖,执行yarn install更新依赖锁 - 删掉application.js中的
import 'animate.css/animate'行 - 移除所有HTML类名的
animate__前缀,修改为:.nav-item.animated.fadeIn.slower.delay-2s Sample Text
内容的提问来源于stack exchange,提问作者Charith Sai
相关产品推荐
相关产品推荐

