新手问题 compass 如何配置编译后的 css 文件名

aNd1coder · 2013年09月30日 · 最后由 aNd1coder 回复于 2013年10月10日 · 3822 次阅读

本人专职前端对 ruby 不熟,在使用 compass 过程中遇到个问题,就是 compass 默认编译xxoo.scssxxoo.css,怎么自定义编译后的文件名(比如xxoo.s.css),不知有描述清楚没,目的就是想xxoo.scss 编译成 xxoo.s.css,非常感谢!

都过节去了么?=.=

如果是 rails, 要写个 xxoo.s.scss

直接把源文件命名为 xxoo.s.scss 不就好了?Compass 只改后缀,文件名是你做主。

#2 楼 @luikore #3 楼 @nightire 目前就是改的.scss 源文件文件名,如果能配置生成的 css 文件名会更好,想做一些命名上的约定...

#4 楼 @aNd1coder 正常的命名约定是原来叫什么出来就叫什么,如果要做和约定不一致的事情,可以自己写编译命令调 scss 命令行生成文件。例如:

input = "xxoo.scss"
output = input.sub /scss$/, "s.css"
system "scss #{input} > #{output}"

另一种方法是加个 "xxoo.s.scss" 然后把对应的 import 进来

@import "xxoo";

#5 楼 @luikore 嗯,非常感谢,就是想走一套自己的命名约定,尽量简洁语义。 compass唯一公开了个config.rb,不想再单开 cmd,第一种方式能配置进去吗? 第二种方法走远了

#6 楼 @aNd1coder

还有种比较土的方法是,在 config.rb 中猴子补丁掉算名字的函数:

module Compass
  module Actions
  end
end
require "compass/compiler"
module Compass
  class Compiler
    def css_files
      sass_files.map{|sass_file| corresponding_css_file(sass_file)}
    end
    def corresponding_css_file(sass_file)
      "#{to}/#{stylesheet_name(sass_file)}.s.css"
    end
  end
end

然后用 ruby -r./config.rb -S compass 代替 compass 命令 (你可以在 ~/.bash_profile 加个 alias compass='ruby -r./config.rb -S compass' 简化以后的调用)

#7 楼 @luikore 再次回来,还是希望能从源头来解决这个问题。 compass 内部应该也是调用的 sass 命令行吧,看能不能从 compass 的源码入手,配置成sass --watch xxoo.scss:xxoo.s.css,找了下源码在这里RailsInstaller\Ruby1.9.3\lib\ruby\gems\1.9.1\gems\compass-0.13.alpha.4\lib\compass\exec@luikore能帮忙找到修改处吗?

#8 楼 @aNd1coder 见我在 #7 楼 给出的解决方案,如果你可以改 compass 源码 (例如自己 fork 一份), 打开 lib/compass/compiler.rb , 找到 corresponding_css_file, 把 ".css" 改成 ".s.css" 就可以。

#9 楼 @luikore 原来#7 给出的就是替换原 compass 的处理方法哈,没看明白来着,不过在 windows 下调用报错,你提到的 compass 源码是我上面给出的 gems 下的文件?隐约感觉这种方式是我想要的,非常感谢@luikore

#10 楼 @aNd1coder 哦不知道是 windows... 对就是你找到的那个目录

#11 楼 @luikore 太棒了,问题已解决,可以请你吃饭么,哥 😆

#11 楼 @luikore 最终打算还是不改源码,采用你在7#的改config.rb方式,不过命令行调用貌似太过复杂(这个是必须的?),windows 下没有alias机制不知怎么处理,添加环境变量进行覆盖貌似也不行。

@luikore 用批处理来解决这个问题了,不过我的config.rb文件里面有定义其他的回调方法会报错

on_stylesheet_saved do |file|
  css = File.read(file)
  File.open(file, 'w') do |io|
    io << AutoprefixerRails.compile(css)
  end
end

错误提示是:

config.rb:21:in `<top (required)>': undefined method `on_stylesheet_saved' for main:Object (NoMethodError)

#14 楼 @aNd1coder

刚想到了个更好的办法避免出错,不改 config.rb, 只用一个 compass.bat, 内容如下:

@ruby.exe -x "%~dpnx0" %*
goto :eof

#!ruby
module Compass
  module Actions
  end
end
require "compass/compiler"
module Compass
  class Compiler
    def css_files
      sass_files.map{|sass_file| corresponding_css_file(sass_file)}
    end
    def corresponding_css_file(sass_file)
      "#{to}/#{stylesheet_name(sass_file)}.s.css"
    end
  end
end

gem 'compass'
load Gem.bin_path('compass', 'compass')

ruby -h 可以看到各参数的含义,例如 -x 参数是忽略 #!ruby 前面的代码

没 windows... 没发现最开始给的代码有点有问题,修改了下

#15 楼 @luikore 测试了下,perfect!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号