Rails_admin为何删除application.css并生成package.json?
问题原因拆解
1. application.css 被删引发的资源找不到错误
Rails Admin 3.1.2 的 --asset=importmap 安装脚本存在 bug,会误删项目里的 app/assets/stylesheets/application.css 文件。而 Rails 默认布局中的 stylesheet_link_tag 'application' 硬依赖这个文件,文件缺失直接触发 Sprockets::Rails::Helper::AssetNotFound 错误。
2. 重复生成 package.json 和调用 npx 的原因
尽管你指定了使用 Importmap,但当前版本的 Rails Admin 安装逻辑在处理样式依赖时,没有完全适配 Importmap 模式——它会默认引入一些 npm 生态的样式处理工具(比如 postcss 相关依赖),导致自动生成 package.json 并调用 npx 执行依赖安装。这属于插件对 Importmap 模式的适配疏漏,没有彻底跳过 npm 相关初始化流程。
修复步骤
步骤1:恢复 application.css 文件
在 app/assets/stylesheets/ 目录下重建 application.css,基础内容如下:
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's * vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any other CSS * files in this directory. Styles in this file should be added after the last require_* statement. * It is generally better to create a new file per style scope. * *= require_tree . *= require_self */
步骤2:清理多余的 npm 文件
删掉自动生成的 package.json 和 package-lock.json(如果存在),Importmap 模式完全不需要这些文件。
步骤3:手动把 Rails Admin 依赖加入 Importmap
打开 config/importmap.rb,添加以下内容:
# Rails Admin 核心脚本与样式 pin "rails_admin", to: "https://ga.jspm.io/npm:rails-admin@3.1.2/app/assets/javascripts/rails_admin.js" pin "rails_admin.css", to: "https://ga.jspm.io/npm:rails-admin@3.1.2/app/assets/stylesheets/rails_admin.css"
然后在 app/javascript/application.js 里导入 Rails Admin 脚本:
import "rails_admin"
如果只需要在 Rails Admin 路由下加载样式,可在布局文件里加判断:
<% if controller.path.start_with?('rails_admin/') %> <%= stylesheet_link_tag "rails_admin", media: "all" %> <% end %>
临时规避方案
如果不想手动折腾,可以暂时回退到 Rails Admin 3.1.1 版本,这个版本对 Importmap 的适配更稳定:
- 在
Gemfile里指定版本:gem 'rails_admin', '~> 3.1.1' - 执行
bundle install - 重新运行安装命令:
rails g rails_admin:install --asset=importmap
内容的提问来源于stack exchange,提问作者Pablo Fernandez

