LoginSignup
13
14

More than 5 years have passed since last update.

cakeコマンドでCoffeeScriptをひとつのjsにまとめる

Posted at

ビルドをプログラミングした Cakefile ファイルを用意して、cake コマンドでいつでもビルドできるようにしておくと大変便利。この例は、foo.coffee, bar.coffee, baz.coffeeをbuild.jsにコンパイルするものです。

Cakefile
util = require('util')
exec = require('child_process').exec

# 設定
SOURCE_DIR = './source'
TARGET_DIR = './build'
TARGET_FILENAME = 'build.js'

#コンパイルするファイル群
files = [
    'foo.coffee'
    'bar.coffee'
    'baz.coffee'
]

# タスクの登録
task 'build', 'CoffeeScriptをまとめてひとつのJavaScriptにします', (options) ->

    # ファイルを構成する
    util.log('まとめるファイルを構成します')
    fileList = []

    for filename, index in files
        file = SOURCE_DIR + '/' + filename
        fileList.push(file)
        util.log("#{index + 1}) #{file}")

    fileList = fileList.join(' ')

    # コンパイルオプション
    option = "-b -cj #{TARGET_DIR}/#{TARGET_FILENAME} #{fileList}"

    # コンパイル実行
    util.log('コンパイルします')
    exec "coffee #{option}", (error, stdout, stderr) -> 

        util.log(error) if error
        util.log(stdout) if stdout
        util.log(stderr) if stderr

        if error
            util.log('失敗しました')
        else
            util.log('成功しました')

使い方とか

cake を叩くと、Cakefileが提供しているタスクの一覧が確認できます。

^_^ (suinair:~/Desktop/project)
* tree .
.
├── Cakefile
├── build
└── source
    ├── bar.coffee
    ├── baz.coffee
    └── foo.coffee

2 directories, 4 files

^_^ (suinair:~/Desktop/project)
* cake
Cakefile defines the following tasks:

cake build                # CoffeeScriptをまとめてひとつのJavaScriptにします

^_^ 3 hits! (suinair:~/Desktop/project)
* cake build
27 Jan 08:47:17 - まとめるファイルを構成します
27 Jan 08:47:17 - 1) ./source/foo.coffee
27 Jan 08:47:17 - 2) ./source/bar.coffee
27 Jan 08:47:17 - 3) ./source/baz.coffee
27 Jan 08:47:17 - コンパイルします
27 Jan 08:47:18 - 成功しました

^_^ 4 hits! (suinair:~/Desktop/project)
* tree .
.
├── Cakefile
├── build
│   └── build.js
└── source
    ├── bar.coffee
    ├── baz.coffee
    └── foo.coffee

2 directories, 5 files
13
14
1

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
13
14