最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - What's the industry standard way to pass SASS variable to javascript? - Stack Overflow

programmeradmin4浏览0评论

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 from

Is there a way to import variables from javascript to sass or vice versa?

I also tried using html

<div class="selector"></div>

with css

.selector { content: "stuff"; }

but looking at the dom in the developer tools, it doesn't get added even though we can see it on the rendered page, so I cannot pick it up with javascript

$('.selector').text()

How does everyone do it?

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 from

Is there a way to import variables from javascript to sass or vice versa?

I also tried using html

<div class="selector"></div>

with css

.selector { content: "stuff"; }

but looking at the dom in the developer tools, it doesn't get added even though we can see it on the rendered page, so I cannot pick it up with javascript

$('.selector').text()

How does everyone do it?

Share Improve this question edited May 23, 2017 at 12:26 CommunityBot 11 silver badge asked Aug 27, 2013 at 4:06 BringMeAnotherBringMeAnother 6272 gold badges10 silver badges18 bronze badges 8
  • You can't pass variables from SASS to JS, the answer you pointed only translated it to JQuery. Anyway, JS is an industry standard, you can always use it combined with CSS ;) – gespinha Commented Aug 27, 2013 at 4:25
  • 5 Perhaps SASS is not meant to be passed to JavaScript, but I can think of at least one place where it would make sense. Suppose I'm making a responsive layout for desktop and mobile. I set my break point at 768px of width in SASS. In JS, it would be useful to know what that breakpoint is instead of declaring a new variable maintain both variables separately. – BringMeAnother Commented Aug 27, 2013 at 4:38
  • @Jack "meant to"? The history of web development is one of clever hacks that solve real world problems. How do you think those cow paths got made in the first place? – steveax Commented Aug 27, 2013 at 6:28
  • @steveax Clever hacks don't sound like an industry standard to me. – Ja͢ck Commented Aug 27, 2013 at 6:37
  • Personally I would see myself define the variables in PHP and pass them to SASS and JS separately. – Ja͢ck Commented Aug 27, 2013 at 6:38
 |  Show 3 more comments

4 Answers 4

Reset to default 10

Not sure about "industry standard", but it's a very handy technique and not too difficult. The content of pseudo elements is not available via text() though, you have to use getComputedStyle.

Example using body:after:

Sass (using the compass breakpoint extension):

body:after {
  display: none;

  @include breakpoint($bp-wide) {
    content: "wide";
  }

  @include breakpoint($bp-medium) {
    content: "medium";
  }

  @include breakpoint($bp-small) {
    content: "small";
  }
}

JavaScript:

if (window.getComputedStyle) {
  var mq = window.getComputedStyle(document.body,':after').getPropertyValue('content');
}

if (mq.indexOf('small') !== -1) {
  // do something
}

Credit: I first saw this technique here: https://coderwall.com/p/_ldtkg

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!

Sharing state trough CSS content property seems dirty. I don't like the idea of making extra XHR requests either.

I've thought of building a custom solution that would just compile SASS file and JS module. But it turned out there's an npm package called rosetta. It does exactly that. Formats of output are pretty flexible and it didn't take me long to set it up as a Grunt.js task.

$ npm install rosetta

Here's example Gruntfile.js:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
      watch: {
          css: {
              files: ['sass/*.scss', 'sass/lib/*.scss', 'rosetta/*.rose'],
              tasks: ['rosetta', 'compass']
          }
      },
      compass: {
          dist: {
              options: {
                  sassDir: 'sass',
                  cssDir: '../static/css',
                  imagesDir: '../static/img',
                  javascriptsDir: '../static/js'
              }
          }
      },
      rosetta: {
          default: {
             src: ['rosetta/*.rose'],
             options: {
                 jsFormat: 'requirejs',
                 cssFormat: 'scss',
                 jsOut: '../static/js/lib/rosetta.js',
                 cssOut: 'sass/_shared_variables.scss'
             }
          }
      }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('rosetta');
  grunt.registerTask('default', ['watch']);

};

And package.json:

{
  "name": "",
  "version": "0.0.0",
  "description": "",
  "main": "Gruntfile.js",
  "dependencies": {
    "grunt": "^0.4.5",
    "grunt-cli": "^0.1.13",
    "grunt-contrib-compass": "^0.9.1",
    "grunt-contrib-watch": "^0.6.1",
    "rosetta": "git+https://github.com/ukolka/rosetta.git"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

After all that you just need to import _shared_variables.scss in SASS and use rosetta.js module in your JavaScript to access common variables. As you make changes to the *.rose files your styles and JS will be updated.

If you are using GULP or GRUNT (I hope you are using the first one)

This example shows how to do it using gulp:

Define the colors in the gulpfile, or in another file and then import it to your gulpfile, and then you can dynamically build both the SCSS variables and the javascript like so:

variables_template.scss (not to be imported in your main scss file)

...
$colors : ([COLORS])
...

app.js (some js file which holds the colors variable)

var appColors = {[COLORS]};

gulpfile.js

var gulp    = require('gulp'),
    gutil   = require('gulp-util'),
    replace = require('gulp-replace');

var appColors = {
   "red"   : "#d63737",
   "green" : "#69c962"
};

gulp.task('scssVars', ()=>{
    var colorsString = JSON.stringify(appColors);
    colorsString  = colorsString.slice(2,colorsString.length - 2);

    return gulp.src('css/variables_template.scss')
        .pipe(replace(/[COLORS]/g, colorsString ))
        .pipe(rename('variables.scss'))
        .pipe(gulp.dest('/'))
});

// do more of less the same for your app.js, only without renaming, if possible

Similar NPM gulp packages for SCSS variables:

  • https://www.npmjs.com/package/gulp-sass-variables
  • https://www.npmjs.com/package/gulp-sass-vars
  • https://www.npmjs.com/package/gulp-json-sass
发布评论

评论列表(0)

  1. 暂无评论