【发布时间】:2023-03-21 01:06:01
【问题描述】:
Shopify 最近决定stop supporting SCSS in their themes。我想将所有 SCSS 文件更改为 CSS,但由于其中包含流动语法,这已成为一场噩梦。这是一个例子:
// Overlays
$color-overlay-title-text: {{ settings.color_image_overlay_text }};
$color-image-overlay: {{ settings.color_image_overlay }};
$opacity-image-overlay: {{ settings.image_overlay_opacity | divided_by: 100.00 }};
{%- comment -%}
Based on the image overlay opacity, either lighten or darken the image on hover
{%- endcomment -%}
{% assign image_overlay_opacity = settings.image_overlay_opacity | divided_by: 100.00 %};
{% if image_overlay_opacity > 0.85 %}
{% assign image_overlay_opacity_hover = image_overlay_opacity | minus: 0.3 %};
{% else %}
{% assign image_overlay_opacity_hover = image_overlay_opacity | plus: 0.4 %};
{% endif %}
$hover-overlay-opacity: {{ image_overlay_opacity_hover | at_most: 1 }};
当我尝试通过在线找到的 scss 编译器运行它时,它在第一个 {{、{% 或 {%- 处失败,因为这不是有效的 scss 语法。我想要的最终结果是一个有效的 css 文件,它保留了流动的语法。
我的下一个想法是预编译文件并将流动语法包装在 unquote("") 或稍后要删除的 css 注释中,然后将其传递给从 here 派生的 ruby scss 编译器。像这样的:
require 'tempfile'
require 'fileutils'
files = ARGV[0]
input_file, output_file = [files.split(":")[0], files.split(":")[1]]
puts "Converting file: #{input_file}"
path_to_compiler = "./lib/ruby-sass/bin/scss"
tmp_path = "./tmp"
# Replace liquid syntax with something SCSS can parse
temp_file = Tempfile.new('tmpscss')
begin
File.open(input_file, 'r') do |file|
file.each_line do |temp_line|
line = temp_line
# Trying to account for edge cases in liquid syntax
if line[0..1] == "{{"
line = line.gsub("{{", "/*lsc {{").gsub("}}", "}} lsc*/")
else
line = line.gsub("{{", "unquote(\"{{").gsub("}}", "}}\")")
end
if line.include?("comment")
line = line.gsub("{%- comment -%}", "/*lsc {%- comment -%}").gsub("{%- endcomment -%}", "{%- endcomment -%} lsc*/")
else
line = line.gsub("{%", "/*lsc {%").gsub("%}", "%} lsc*/")
end
temp_file.puts line
end
end
temp_file.close
FileUtils.mv(temp_file.path, tmp_path)
puts "#{temp_file.path}:#{output_file}"
# Pass to SCSS compiler
system "ruby #{path_to_compiler} -C .#{temp_file.path}:#{output_file}"
ensure
temp_file.close
temp_file.unlink
end
puts "Output file to: #{Dir.pwd}/#{output_file}"
这几行就成功了,但是我试图解析的原始逻辑有太多的边缘情况,scss到css的转换不可避免地会失败。必须有更好的方法来做到这一点。有人有什么想法吗?我希望 Shopify 允许我们使用他们的 SCSS 编译器。
【问题讨论】: