Different SASS/Coffeescript Variable Values Based

2019-05-10 17:02发布

问题:

I am trying to create a build system for a front-end framework that will create different paths in SASS (and possibly Coffeescript) based on where I am deploying to. So for example, I might have an image file I am referencing in my SASS locally in ../images/image.png, and this works fine in my local environment. However, my client has a very locked down environment that has to be done in a different way (getting their images from a CDN). So their image path might look like ~Some_service_call/images/image.png.

What I'm hoping to do is have some sort of configuration ready for both environments, so when I'm developing locally I can either run a command via Terminal like build local package or build deploy package that would automatically recognize what environment I am deploying to and use a path based on that. I would ideally have a separate config JSON file that controls which paths to use for each SASS / Coffeescript variable.

So far I've been beginning to look into Grunt for this, but not sure it's the correct solution. Has anyone ever tried to do this type of thing, and what worked/didn't work for you?

回答1:

Use Compass to compile your projects.

In Compass's config.rb define a custom function:

# Assign a name to the project and pass it into SASS
$environment = "development"
module Sass::Script::Functions
  def environment
    Sass::Script::String.new($environment)
  end
end

This function will become available in SASS:

$images-root: ".."
@if environment() == production
  $images-root: "/var/www/static/images"

html
  background-image: url( #{$images-root + "/sexy-lady.png"} )

And you can customize that to your lining! For example, you can pass the paths to SASS. Or you can create a separate Ruby file with some advanced logic (service calls, reading JSON), require it from config.rb and pass to SASS functions.

Finally, you write a small script that updates the info and runs compass compile.

PS Compass also allows adding debug information for development and CSS minification for production.



回答2:

If you don't want to create a config.rb, just use the option environment in gruntfile.js and set it to production or development:

compass: {          
            prod: {
                options: {                  
                    environment: 'production'
                }
            },
            dev: {
                options: {
                    environment: 'development'
                }
            }
        }

and the environment value will be available at file.scss or file.sass file:

$font-path: "../fonts";

@if compass-env() == 'production'
{
    $font-path: "../assets/fonts"
}