Skip to content

Instantly share code, notes, and snippets.

@geta6
Last active December 23, 2015 15:39
Show Gist options
  • Save geta6/6657231 to your computer and use it in GitHub Desktop.
Save geta6/6657231 to your computer and use it in GitHub Desktop.

中二病でもCoffeeをGruntしたい

test

  • Grunt4の使い方
  • 13.09.22 @masuilab

What is Grunt???

Grunt is

  • Node.js製のタスクランナー
  • ビルドやテストランの自動化

なにができるの

  • Compile
    • coffee, stylus, jade …
  • Test
    • mocha, jslint …
  • Function
    • concat, watch …
  • and more…

どういうことができるの

  • assets/js/*.coffeepublic/js/*.jsへコンパイルしたい
  • コードに変更があったら自動でコンパイルしてほしい
  • livereloadとかもしてくれたら開発強度高まる
  • デプロイをかけたらmochaでテストを走らせてほしい

依存

  • node, npmが必要です

事始め

  • grunt-cliをインスコします
  • npm -g i grunt-cli
  • grunt本体はプロジェクトへ個別にインストールします

Gruntfile

  • Gruntfile.jsまたはGruntfile.coffeeをルートディレクトリに作ります

空のGruntfileを作る

coffeeでやります

module.exports = (grunt) ->
  grunt.initConfig
    pkg: grunt.file.readJSON 'package.json'
    # grunt.loadNpmTasks ''
    grunt.registerTask 'default', []
  • module.exports: nodeのアレ
  • initConfig: ここにモジュールの設定を書きます
  • loadNpmTasks: npmのモジュールをロードします
  • registerTask: タスクのエイリアスを作ります、複数のタスクをまとめるなど

Gruntをインストールする

npm i grunt --save-dev

実行方法

grunt [task]

taskを省略した場合はdefaultが実行されます

Coffeeモジュールを入れる

npm i grunt-contrib-coffee --save-dev

Coffee

initConfigに設定を追加します

grunt.initConfig
  coffee:
    compile:
      files: [{
        expand: yes            # destが無い場合に mkdir -p
        cwd: 'assets/'         
        src: [ '**/*.coffee' ] # パターン
        dest: 'public/'        
        ext: '.js'             
      }]

grunt.loadNpmTasks 'grunt-contrib-coffee'

実行する

grunt coffee

initConfigの設定名がtask名になります

watchもしちゃう

% npm i grunt-contrib-watch --save-dev

grunt.initConfig
  watch:
    coffee:
      files: ['assets/**/*.coffee']
      tasks: ['coffee']

grunt.loadNpmTasks 'grunt-contrib-watch'

% grunt watch

基本的にこれだけ

  • contribをインストールして
  • 設定を書き足して
  • モジュールのローダーを書いて
  • 実行
module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
jade:
compile:
files: [{
expand: yes
cwd: 'assets/'
src: [ '*.jade' ]
dest: 'public/'
ext: '.html'
}]
coffee:
compile:
files: [{
expand: yes
cwd: 'assets/'
src: [ '**/*.coffee' ]
dest: 'public/'
ext: '.js'
}]
stylus:
compile:
files: [{
expand: yes
cwd: 'assets/'
src: [ '**/*.styl' ]
dest: 'public/'
ext: '.css'
}]
watch:
options:
livereload: yes
coffee:
files: ['assets/**/*.coffee']
tasks: ['coffee']
jade:
files: ['assets/*.jade']
tasks: ['jade']
stylus:
files: ['assets/**/*.styl']
tasks: ['stylus']
connect:
livereload:
options:
port: 35729
grunt.loadNpmTasks 'grunt-contrib-jade'
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-stylus'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.registerTask 'default', ['watch']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment