LoginSignup
20
20

More than 5 years have passed since last update.

GruntでCompassの自動ビルドを行う

Posted at

GruntはJSのタスク実行ツールです。

CoffeeScriptのコンパイル、{Cofffee,Java}Scriptの文法チェック、JS/CSSのminify、テスト実行等、様々なタスクを走らせることができます。

GruntでCompassの自動ビルド設定を行うことで、scssファイルの変更を検知して自動的にcssを出力させることができます。

compass自体にもこの機能はありますが、gruntで設定しておくことで他のタスクも実行できるので、後々効いてきます。

Grunt-cliのインストール

Gruntは、Node.jsで動作しますので、まずはNode.jsをインストールしてください。

Macであれば、brew install nodeでおしまい。

gruntコマンドはnpmパッケージでインストールします。頻繁に使うコマンドですので、グローバルにインストールしておきましょう。

npm install -g grunt-cli

package.jsonの準備

gruntには便利なプラグインがたくさんありますが、プロジェクト毎に使うものが異なりますので、プロジェクトフォルダにpackage.jsonを作成し、このファイルに必要なnpmパッケージを登録します。

以下のコマンドを実行し、対話的に情報を入力していくことで、package.jsonが生成されます。

入力は基本的にEnterのみでOK。

npm init

必要なnpmパッケージの追加

gruntで自動実行させるために必要なnpmパッケージをインストールします。
--save-devオプションを付けることで、自動的にpackage.jsonにも記述されます。

npm install grunt grunt-contrib-compass grunt-contrib-watch load-grunt-tasks --save-dev
  • grunt: grunt本体
  • grunt-contrib-compass: compassタスク
  • grunt-contrib-watch: フォルダ自動監視タスク
  • load-grunt-tasks: npmで入れたgruntタスクの自動ロード用

Gruntfileの作成

Gruntfileは基本はJSですが、CoffeeScriptでも記述できます。(その場合は Gruntfile.coffee)

  • compassのconfig.rbのパス: src/config.rb
  • sass/scssのパス: src/sass/*

だとすると、

Gruntfile.coffee
module.exports = (grunt) ->
  require('load-grunt-tasks') grunt

  grunt.initConfig
    compass:
      devel:
        options:
          config: 'src/config.rb'
          environment: 'development'
          bundleExec: true
      prod:
        options:
          config: 'src/config.rb'
          environment: 'production'
          bundleExec: true

    watch:
      compass:
        files: 'src/sass/*'
        tasks: 'compass:devel'

Gruntタスクの実行

grunt watchでwatchタスクを実行しておくことで、ファイルの修正を検知して自動的にcompass:develタスクを実行します。

  • compass:devel - development環境でビルドします。scssの行番号等のコメントを入れたcssが生成されます。開発時に便利。
  • compass:prod - production環境でビルドします。未圧縮で公開したい場合に便利。

ソースファイルが全く変更されていない場合はcompassのビルドが省略されます。
devel/prodの切り替えの際は生成済みのcssを一旦削除する等の作業が必要な場合がありますのでご注意を。

このあたりもgruntタスクで上手く処理する方法があります。

20
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20