我正在构建一个带有jQuery
和其他一些库的Rails 5.1.x rails应用程序。Rails坚持使用Yarn,这在开发机器上很好,但我不能在生产中使用它。
有没有办法让导轨默认不使用 Yarn?删除yarn.lock
和node_modules
以及随之而来的其他所有内容。
从文件中删除以下行
bin/setup.rb 和 bin/update.rb
- # Install JavaScript dependencies if using Yarn
- system('bin/yarn')
config/initializers/assets.rb
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')
在 Rails5.2.x 和 6.0.x 中,如果您使用 --skip-yarn 标志创建新的 Rails 应用程序,它仍然会添加检查是否安装了 yarn。 所以当你运行rails webpacker:install
时,结果可能是
Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/
解决方案是在 Rakefile 的末尾添加这四行,紧跟在Rails.application.load_tasks
之后:
# Replace yarn with npm
Rake::Task['webpacker:yarn_install'].clear
Rake::Task['webpacker:check_yarn'].clear
Rake::Task.define_task('webpacker:verify_install' => ['webpacker:check_npm'])
Rake::Task.define_task('webpacker:compile' => ['webpacker:npm_install'])
这将删除对纱线的检查,并且您只能使用 webpack。
编辑:如果你使用资产编译,或者你想管理客户端库,比如 React、Angular 或 Vue,我实际上建议使用 yarn 而不是 npm,因为 Rails 6 似乎与yarn深度集成。它将在服务器启动时调用 yarn,也会在资产编译时调用 yarn。与其费力地用npm替换yarn,不如接受Rails repo开发人员的选择。
创建 rails 项目时,可以将--skip-yarn
添加为rails new app_path --skip-yarn
。
提醒将来阅读这个问题的人:Max Popoff 的答案只有在您首先定义其 Rakefile 中引用的新 rake 任务时才有效。这篇博文中有更多信息,但本质上,您需要添加这样的文件:
# lib/tasks/webpacker.rake
namespace :webpacker do
task :check_npm do
begin
npm_version = `npm --version`
raise Errno::ENOENT if npm_version.blank?
version = Gem::Version.new(npm_version)
package_json_path = Pathname.new("#{Rails.root}/package.json").realpath
npm_requirement = JSON.parse(package_json_path.read).dig('engines', 'npm')
requirement = Gem::Requirement.new(npm_requirement)
unless requirement.satisfied_by?(version)
$stderr.puts "Webpacker requires npm #{requirement} and you are using #{version}" && exit!
end
rescue Errno::ENOENT
$stderr.puts 'npm not installed'
$stderr.puts 'Install NPM https://www.npmjs.com/get-npm' && exit!
end
end
task :npm_install do
system 'npm install'
end
end