Last active
April 10, 2018 15:23
-
-
Save iantheparker/a2c4299918ea1470162c1a79c3c86a91 to your computer and use it in GitHub Desktop.
Resolve Yarn assets for Cloudfront in Sprockets/Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
desc "resolve_asset paths installed via Yarn" | |
task :resolve_assets => :environment do | |
components_directory = 'node_modules' | |
root_directory = components_directory | |
# Resolve relative paths in CSS | |
Dir["#{components_directory}/**/*.css"].each do |filename| | |
contents = File.read(filename) if FileTest.file?(filename) | |
# http://www.w3.org/TR/CSS2/syndata.html#uri | |
url_regex = /url\((?!\#)\s*['"]?((?![a-z]+:)([^'"\)]*?)([?#][^'"\)]*)?)['"]?\s*\)/ | |
# Resolve paths in CSS file if it contains a url | |
if contents =~ url_regex | |
directory_path = Pathname.new(File.dirname(filename)) | |
.relative_path_from(Pathname.new(root_directory)) | |
# Replace relative paths in URLs with Rails asset_path helper | |
new_contents = contents.gsub(url_regex) do |match| | |
relative_path = $2 | |
params = $3 | |
image_path = directory_path.join(relative_path).cleanpath | |
puts "Resolving asset: #{match} => #{image_path} #{params}" | |
"url(<%= asset_path '#{image_path}' %>#{params})" | |
end | |
# Replace CSS with ERB CSS file with resolved asset paths | |
FileUtils.rm(filename) | |
File.write(filename + '.erb', new_contents) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put that file in your lib/tasks directory and call it
from your Rakefile with