albatrosary's blog

UI/UXとエンタープライズシステム

gruntを使おう 〜 ファイルの内容を変えるプラグインだyo 〜

gruntを使ってリリースモジュールを作成する際にまれにindex.htmlとかファイルの内容を変えたいときがあります。たとえば

  • index.htmlにモック開発時のテストコードが入っているが本番では利用しない
  • 本番のディレクトリ構成が特殊でリリース時に<script src="scripts/main.js">を変更したい

こんなときに使えるのが grunt-text-replace です。

 

インストール

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

Guntfile.jsでの読み込み

grunt.loadNpmTasks('grunt-text-replace');

特定のファイルの中の文字列を変更する場合

次のように置換します。

replace: {
  another_example: {
    src: ['build/*.html'],
    overwrite: true,                 // overwrite matched source files
    replacements: [{
      from: /[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4}/g,
      to: "<%= grunt.template.today('dd/mm/yyyy') %>"
    }]
  }
}

変更したいファイルをsrcに記載します。

overwite: trueと記述することでファイルを上書きします。

replacementsのfromで置換対象の文字、toで置換後の文字に変換できます。

特定のファイルの中の文字列を変更し別のディレクトリへ出力する場合

replace: {
  example: {
    src: ['text/*.txt'],             // source files array (supports minimatch)
    dest: 'build/text/',             // destination directory or file
    replacements: [{
      from: 'Red',                   // string replacement
      to: 'Blue'
    }, {
      from: /(f|F)(o{2,100})/g,      // regex replacement ('Fooo' to 'Mooo')
      to: 'M$2'
    }, {
      from: 'Foo',
      to: function (matchedWord) {   // callback replacement
        return matchedWord + ' Bar';
      }
    }]
  }
}

replacementsは複数パターン定義することができます。またexampleに関してもexample2、example3・・と複数定義できます。JavaScriptのとかCSSのとか色々定義できますのでリリース時に変更したい文字列を置換することができます。

最後に

繰り返しになりますが、まれにファイルの内容を変更したい場合があります。そんなときに使える便利なプラグインです。