22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Gruntjsでutf-8のhtmlをshift-jisにして出力する方法

Posted at

shift-jisのhtmlを出力したいとき、
出力元htmlはutf8にして出力先htmlをshift-jisにすれば、
includereplaceなどでhtml結合しても文字化けなどに悩まされずに済みます。

package.json

{
  "name": "grunt_encoding",
  "version": "0.0.0",
  "description": "file encofing sample",
  "author": "svartalfheim",
  "license": "MIT",
  "devDependencies": {
    "grunt": "^0.4.5",
    "grunt-contrib-copy": "^0.5.0",
    "iconv-lite": "^0.4.3"
  }
}

Gruntfile.js

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

module.exports = function(grunt) {

  var pkg = grunt.file.readJSON('package.json');

  // Project configuration.
  grunt.initConfig({
    copy:{
        html:{
            options:{
                encoding:'utf8',
                process:function( content ){
                  return iconvLite.encode(new Buffer(content),'shift_jis');
                }
            },
            files:{
                'dst/index.html':'src/index.html'
            }
        }
    }
  });

  // These plugins provide necessary tasks.
  Object.keys(pkg.devDependencies).forEach(function (devDependency) {
      if (devDependency.match(/^grunt\-/)) {
          grunt.loadNpmTasks(devDependency);
      }
  });

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

};

ポイントはiconv-lite (https://github.com/ashtuchkin/iconv-lite) を用いてgrunt-contrib-copyのoptions.processで文字コードの変換処理をいれてコピーしてあげることです。

22
21
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
22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?