10

I am building a script in Ruby where I would like to compile a single SCSS file using Compass. I am trying to make this as simple as possible, and would like to avoid using a config.rb file. I just want to set a couple settings via straight Ruby and tell Compass to compile a single SCSS file into a CSS file.

I know that this has to be possible but I have not been able to find any decent documentation on how to do it. Any help would be appreciated.

4

2 回答 2

10

你是对的,实际上并没有任何关于如何在 Ruby 中使用 Compass 的全面文档。这很不幸,但我们不要让文档等小细节阻止我们!

第一次尝试

当我想做同样的事情时,我只是浏览了 Compass源代码,并能够将这个小 Ruby 脚本放在一起。乍一看,它似乎可以解决问题:

require 'compass'
require 'sass/plugin'

compiler = Compass::Compiler.new(
    # Compass working directory
    '.',
    # Input directory
    'styles/scss',
    # Output directory
    'styles/css',
    # Compass options
    { :style => :compressed }
)

compiler.compile('test.scss', 'test.css')

但显然 Compass 有一堆默认配置选项,在直接调用编译器构造函数时不会自动包含这些选项(其中 SASSload_path就是其中之一)。在尝试导入 Compass 函数和 mixin 时,这可能会导致错误,例如:

错误:找不到要导入的文件或无法读取:compass/css3

指南针 <1.0.0(又名“旧方式”)

以下是如何在覆盖这些默认值的情况下调用编译器:

require 'compass'

Compass.add_configuration(
    {
        :project_path => '.',
        :sass_path => 'styles/scss',
        :css_path => 'styles/css'
    },
    'custom' # A name for the configuration, can be anything you want
)
Compass.compiler.compile('test.scss', 'test.css')

但是,从 Compass 版本 1.0.0 开始,Compass.compiler已弃用,支持 . Compass.sass_compiler,导致...

指南针 >=1.0.0(又名“新方式”)

感谢@philipp发现如何使用新 API,我们可以再次更新此代码段以使用Compass.sass_compiler

require 'compass'
require 'compass/sass_compiler'

Compass.add_configuration(
    {
        :project_path => '.',
        :sass_path => 'styles/scss',
        :css_path => 'styles/css'
    },
    'custom' # A name for the configuration, can be anything you want
)

compiler = Compass.sass_compiler({
  :only_sass_files => [
    'styles/scss/test.scss'
  ]
})

compiler.compile!
于 2012-10-30T12:55:21.017 回答
0

只需从命令行调用编译方法。您可以在那里指定每个选项。要查看所有选项,请运行compass help compile.

下面是一个例子。它将在与 test.scss 文件相同的目录中输出编译后的 css 文件。

file_name = "absolute/path/to/test.scss"
system "compass compile #{file_name} --sass-dir . --css-dir ."

您可以根据需要指定和插入任意数量的选项。还要检查这个是否在 ruby​​ 中运行命令:

在 Ruby 脚本中运行命令行命令

于 2012-10-30T09:46:08.840 回答