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

后端 未结 4 757
夕颜
夕颜 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条回答
  •  萌比男神i
    2020-12-15 22:21

    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.

提交回复
热议问题