LoginSignup
13
13

More than 5 years have passed since last update.

Grunt で、utf-8 で開発を行いながら shift_jis のファイルを自動生成する方法

Last updated at Posted at 2015-02-12

問題

Grunt では shift_jis のファイルをうまく扱うことができません。

特に、grunt-contrib-connect などで立てたローカルサーバで shift_jis の HTML ファイルを表示すると文字化けしてしまい、使い物になりません。

解決策

普段通り utf-8 で開発を行いながら、shift_jis のファイル群も生成する Grunt タスクを作成しました。

以下のようなディレクトリ構造を想定しています。

├─Gruntfile.js
├─package.json
├─sjis   【shift_jis のファイル群を自動生成するディレクトリ】
│  └─
│
└─utf8   【utf-8 で普段通り作業をするディレクトリ】
    ├─css
    ├─img
    ├─js
    └─index.html

Gruntfile は下記になります。

Gruntfile.js
module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');

  var iconvLite = require('iconv-lite');


  grunt.initConfig({

    watch: {
      files: [ 'utf8/**/*' ], // (1)
      tasks: [ 'clean', 'copy' ]
    },

    clean: {
      sjis: ['sjis/*'] // (2)
    },

    copy: {
      copy_html: {
        files: [
          {expand: true, cwd: 'utf8/', src: ['**/*.html'], dest: 'sjis/'} // (3)
        ],
        options: {
          encoding :'utf8',
          process: function( content ){
            var replacedContent = content.replace('<meta charset="utf-8">', '<meta charset="Shift_JIS">'); // (4)
            return iconvLite.encode(new Buffer(replacedContent), 'shift_jis'); // (5)
          }
        }
      },
      copy_css: {
        files: [
          {expand: true, cwd: 'utf8/', src: ['**/*.css'], dest: 'sjis/'} // (3)
        ],
        options: {
          encoding: 'utf8',
          process: function( content ){
            var replacedContent = content.replace('@charset "UTF-8";', '@charset "Shift_JIS";'); // (4)
            return iconvLite.encode(new Buffer(replacedContent), 'shift_jis'); // (5)
          }
        }
      },
      copy_js: {
        files: [
          {expand: true, cwd: 'utf8/', src: ['**/*.js'], dest: 'sjis/'} // (3)
        ],
        options: {
          encoding: 'utf8',
          process: function( content ){
            return iconvLite.encode(new Buffer(content), 'shift_jis'); // (5)
          }
        }
      },
      copy_others: {
        files: [
          {expand: true, cwd: 'utf8/', src: ['**', '!**/*.html', '!**/*.css', '!**/*.js'], dest: 'sjis/'} // (6)
        ]
      }
    }

  });

  grunt.registerTask('default', [ 'watch' ]);

};

解説

  1. utf8/ 以下を監視し、更新があると
  2. sjis/ 以下をいったん全削除し
  3. utf8/ 以下の html、css、js ファイルを対象にして
  4. charset の指定を Shift_JIS に置き換えたうえで
  5. 文字コードを Shift_JIS に変換して sjis/ 以下にコピーして
  6. 残ったファイルはそのまま sjis/ 以下にコピーする

ということをしています。

これで utf-8 で作業をしながら shift_jis のファイル群を生成することができるので、あとは好きなタスクを追加して快適な環境で開発ができます。

参考

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