What's the industry standard way to pass SASS variable to javascript?

后端 未结 4 772
夕颜
夕颜 2020-12-15 21:48

I have looked around and I\'ve seen one solution where in your html, you\'d have a tag dedicated to pass sass variables to javascript. I\'m talking about the second answer f

4条回答
  •  清酒与你
    2020-12-15 22:34

    I believe that injecting SASS variables via CSS content property is a very hackish way to do things.

    Instead, you can store the variables in a separate location and have them read both by SASS and JS.

    First, store a list of breakpoints in a breakpoints.json file:

    ["0", "300px", "500px", "700px", "900px", "1100px"]
    

    Then use Ruby to read this JSON file and make its contents available as a SASS list via a SASS function. Put this into your Compass config.rb:

    sass_options = { :custom => {'breakpoint_file' => 'breakpoints.json'} }
    
    # This creates a SASS function debug() that returns $debug into SASS
    module Sass::Script::Functions
      def breakpoints
    
        # Reading an array of breakpoints into a file
        unless breakpoints_array_raw = JSON.load( IO.read( options[:custom]['breakpoint_file'] ))
          raise Sass::SyntaxError.new("Error: Breakpoints file '#{options[:custom]['breakpoint_file']}' does not exist.")
        end
    
        # Converting strings in the array to SASS String literals
        breakpoints_array_sassy = breakpoints_array_raw.map { |s| Sass::Script::String.new(s) }
    
        # Returning the list into SASS
        Sass::Script::List.new( breakpoints_array_sassy, :space )
      end
    end
    

    In your SASS code, read breakpoints like this:

    $breakpoints: breakpoints()
    

    In JS, use jQuery's .get method to request the JSON file like this:

    var
      breakpoints = [],
      requestBreakpoints = $.get('breakpoints.json');
    
    requestBreakpoints.done(function (response, textStatus, jqXHR){
        breakpoints = response; // You might want to remove "px" here
    });
    

    When i was assembling this setup, I found an existing solution here, but i decided to reimplement it using my favorite SASS tools: Singularity and Breakpoint Slicer.

    For your convenience, i've built a proof-of-concept GitHub project with everything set up nicely, featuring some ugly JS code. :)

    And here's a live demo!

提交回复
热议问题