STYLE SWITCHER

Compile imported regular CSS file in SCSS file to SASS @import rule

With SASS and Compass, all the imported SCSS and SASS files can be compressed and merged into a single CSS output file. What about the regular CSS files? According to this documentation all files with .css extension, it will be compiled to a CSS @import rule.

For example, if style.scss contains:

@import "../../bower_components/animate.css/animate.css";

… it will be compiled to:

@import url(../../bower_components/animate.css/animate.css);

This is not what we want if we are aiming to utilize the minify and merge features of SASS and Compass. Some will rename the .css fileextension to .scss as workaround. But if we are using a package manager like Bower, renaming the file extension is strongly not recommended. This article will show solution to this issue:

In your project folder, create mylib.rb file and copy the following codes in this file:

require "sass/importers"
class Sass::Importers::Filesystem
  alias :css_importer :extensions
  def extensions
    css_importer.merge('css' => :scss)
  end
end

Now we can import regular CSS file(s) in our SASS files. Example if we want to import ../../bower_components/animate.css/animate.css we will write it in SASS file without the .css extension:

@import "../../bower_components/animate.css/animate";

To use our custom ruby library with the compass command line, execute:

compass compile assets/sass/style.scss -r ./mylib.rb

If you are using grunt, you can use the following codes as the reference for your gruntfile.js:

odule.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.initConfig({
    compass: {
      prod: {
        options: {
          config: 'config.rb',
          require: './mylib',
          environment: 'production',
          sourcemap: true
        } // options
      }, // prod
      dev: {
        options: {
          config: 'config.rb',
          require: './mylib',
          sourcemap: true
        } // options
      } // dev
    }, // compass
    watch: {
      sass: {
        files: [
          'assets/sass/*.scss'
        ],
        tasks: ['compass:dev']
      } // sass
    } // watch
  }); // initConfig
  grunt.registerTask('default', 'watch');
  grunt.registerTask('prod', ['compass:prod']);
} // exports

Recent Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. Joel Philip at 10:18 am

    Thanks for the useful tips Anish. Keep posting. I can always recommend CodeHints.