Skip to content

Instantly share code, notes, and snippets.

@dmshvetsov
Last active July 30, 2022 00:02
Show Gist options
  • Save dmshvetsov/a10b85b492e2d8b9e12b19005ccd3d7c to your computer and use it in GitHub Desktop.
Save dmshvetsov/a10b85b492e2d8b9e12b19005ccd3d7c to your computer and use it in GitHub Desktop.
Use rails webpacker gem with npm instead of yarn, Rails recipe.
# config/environments/development.rb
Rails.application.configure do
config.webpacker.check_yarn_integrity = false
# the rest of the file is omitted
# config/environments/production.rb
Rails.application.configure do
config.webpacker.check_yarn_integrity = false
# the rest of the file is omitted
# Rakefile
require File.expand_path('../config/application', __FILE__)
Rails.application.load_tasks
# Replace yarn with npm
Rake::Task['yarn:install'].clear if Rake::Task.task_defined?('yarn:install')
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'])
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment