Compass 编译和 WordPress 主题

Avatar of Chris Coyier
Chris Coyier 发表

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

如果您是 WordPress 主题构建者 并且是 Sass/Compass 用户,首先,哇,您太棒了!其次,您可能会遇到一个关于编译位置的小问题,所以我们现在就来解决它。

关于 CSS 和 WordPress 主题,有两件非常重要的事情

  1. 主题文件夹中绝对必须存在一个“style.css”文件。
  2. 该文件绝对必须以这样的注释块开头
/*
Theme Name: Twenty Ten
Theme URI: http://wordpress.org/
Description: The 2010 default theme for WordPress.
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 1.0
Tags: black, blue, white, two-columns, fixed-width, custom-header, custom-background, threaded-comments, sticky-post, translation-ready, microformats, rtl-language-support, editor-style, custom-menu (optional)

License:
License URI:

General comments (optional).
*/

如果该文件不存在或注释块丢失,WordPress 甚至无法识别该主题。

如果您使用 Sass/Compass 并且您的主题具有一个**非常简单的**样式表,也许它都在一个文件中,并且您只有一个这样的目录

/wp-content
  /themes
    /your-theme
       config.rb
       index.php 
       style.scss
       style.css

您的 config.rb 文件(用于 Compass)非常标准,如下所示

http_path = "/"
css_dir = ".."
sass_dir = ".."
images_dir = "images"
javascripts_dir = "js"

output_style = :compressed
environment = :development

这样就可以了。您已经设置好了。您只需要确保在 style.scss 文件顶部的注释中使用“!”,这样即使在编译/压缩发生时,注释也会保留下来

/*!
Theme Name: Your Theme

etc...
*/

问题

我们中的许多人没有那么简单的设置。我喜欢用我的 Sass 分块工作,而不是把所有东西都塞进一个文件里。我更喜欢在我的主题中拥有 css 和 scss 文件夹。像这样

/wp-content
  /themes
    /your-theme
       /css
          site-sub-section.css
       /scss
          _grids.scss
          _normalize.scss
          _typography.scss
          site-sub-section.scss
       config.rb
       index.php 
       style.scss
       style.css

问题是没有 Compass 配置允许这些编译路径。

compile-no
显然不会发生。(这是一个简化的 WordPress 主题目录。想象更多文件。)

解决方案

  1. 将您的配置设置为更标准的将 scss 文件夹编译到 css 文件夹中。
  2. 将 style.scss 文件夹移动到 scss 文件夹中。
  3. 成功将 style.scss 编译到 style.css 后,自动将 style.css 移动到根文件夹。

新的 config.rb

http_path = "/"
css_dir = "css"
sass_dir = "scss"
images_dir = "images"
javascripts_dir = "js"

output_style = :compressed
environment = :development

显然,您在 config.rb 中编写的任何代码都会在每次编译时运行,因此为了完成第 3 步,我们可以在特定事件发生时编写 Ruby 代码以执行。在我们的例子中,当样式表保存时(Compass 完成编译),我们检查该文件是否名为“style.css”,如果是,则将其向上移动一个目录。puts 语句只是为了让您能够在需要时从命令行观察它工作。

require 'fileutils'
on_stylesheet_saved do |file|
  if File.exists?(file) && File.basename(file) == "style.css"
    puts "Moving: #{file}"
    FileUtils.mv(file, File.dirname(file) + "/../" + File.basename(file))
  end
end

感谢 Christopher Eppstein 向我展示了它是如何工作的。