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

后端 未结 4 755
夕颜
夕颜 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:29

    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

提交回复
热议问题