grunt-text-replaceでテキスト置換

2013.04.17

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

テキスト置換を一括で

最近お気に入りのGruntの話です。
Gruntではテキスト置換もプラグインを使って簡単にできます。

環境構築方法

今回使用した動作環境は以下のとおりです。

  • OS : MacOS X 10.7.4
  • Node.js : v0.10.0
  • npm : 1.2.14
  • Grunt : 0.41

grunt-cliをグローバルオプションを付けてインストールしておきます。

% npm install -g grunt-cli

そして、npmを使ってpackage.jsonを作成しましょう。

% mkdir grunt-replace
% cd grunt-replace
% npm init //全部デフォルトで作成

最後に、gruntモジュールとgrunt-text-replaceモジュールのインストールをしておきましょう。
--save-devオプションをつけると、package.jsonにそのモジュールが追加されます。

% npm install grunt --save-dev
% npm install grunt-text-replace --save-dev

Gruntの動作を定義する、Gruntfile.coffeeを作成します。

module.exports = (grunt) ->
  pkg = grunt.file.readJSON 'package.json'
  grunt.initConfig
    replace:
      example1:
      	src: ['text/*.txt'],
      	dest: 'build/text/',
      	replacements: [{
      	  from: 'Red',
      	  to: 'Blue'
      	  }, { 
      	  from: /<deploy_date>/g,
      	  to: "<%= grunt.template.today('yyyy/mm/dd') %>"
      	}]
      example2:
      	src: ['text2/*.txt'],
      	overwrite: true,
      	replacements: [{ 
          from: /hello/g,
          to: (matchedWord, index, fullText, regexMatches) ->
          	  'planet'
        }]

  grunt.loadNpmTasks 'grunt-text-replace'

example1タスクはtextディレクトリ下のtxtファイルに対して実行され、置換結果はbuild/text以下に出力されます。
Redという文字列はBlueに置き換えられ、<deploy_date>という文字列は今日の日付に置き換えられます。
textディレクトリとbuildディレクトリを作成し、下記のようなtxtファイルを作成してGruntを実行してみましょう。

#test.txt
Red
Blue
Yellow
<deploy_date>
aaaa
bbbb
hello

example1タスクを実行します。

% grunt replace:example1
Running "replace:example1" (replace) task

Done, without errors.

build/text/test.txtは下記のように置換されているはずです。

#test.txt
Blue
Blue
Yellow
2013/04/17
aaaa
bbbb
hello

もう1つ例をみてみましょう。example2タスクはtext2ディレクトリ下のtxtファイルに対し、
helloという文字列をplanetに書き換えます。
overwrite: trueというオプションをつけておけば、自身を書き換えることができます。
toプロパティは関数を指定することも可能で、マッチした文字列や対象文字列全体の情報も参照することができます。
text2ディレクトリを作成してtxtファイルを作成し、example2を実行してみましょう。

% grunt replace:example2
Running "replace:example1" (replace) task

Done, without errors.

text2ディレクトリ下のtxtファイルが置換されています。

まとめ

ソースにヘッダー/バージョン/日付を入れるなど、いろいろ使えそうですね。

参考サイトなど