オリジナルのアイコンをアイコンフォント化して使用する機会があったので、gulpでアイコンフォントを作成してみました。
フォルダ構成
/
├ package.json
├ gulpfile.js
├ node_modules/
└ dev/
├ icons/ ←アイコンフォント用svgファイルを格納【A】
├ *.svg
└ templates/
└ iconfont.css ←テンプレートcssファイル【B】
├ fonts/ ←gulpで生成したアイコンフォントの格納場所【C】
├ iconfont.eot
├ iconfont.svg
├ iconfont.ttf
└ iconfont.woff
└ css/ ←gulpで生成したcssファイル【D】
svgファイルの作成【A】
gulp-iconfont というプラグインを使ってアイコンフォントを作成するので、注意点を確認してからsvgファイルを作成してください。
下記URLからSVGファイルをダウンロードすることもできます。
https://github.com/backflip/gulp-iconfont-css/tree/master/test/fixtures/icons
Beware that your SVG icons must have a high enough height. 500 is a minimum. If you do not want to resize them, you can try to combine the fontHeight and the normalize option to get them in a correct size.
テンプレートcssファイルの用意【B】
こちらのcssファイルを使用させていただきました。
https://github.com/backflip/gulp-iconfont-css/blob/master/templates/_icons.css
※今回作成したgulpfileではファイル名を「iconfont.css」に変更しました。
パッケージのインストール
※gulpの導入については省略します。
以下のパッケージを使用しました。
- gulp
- gulp-iconfont
- gulp-consolidate
- lodash
コマンドを実行してパッケージをインストールします。
$ npm intsall --save-dev パッケージ名
gulpfileにタスクを記述する
// パッケージの読み込み
// ------------------------------------------
var gulp = require('gulp'),
iconfont = require('gulp-iconfont'),
consolidate = require('gulp-consolidate');
/***************************************************************************
* アイコンフォント
***************************************************************************/
var runTimestamp = Math.round(Date.now()/1000);
gulp.task('iconfonts', function(){
return gulp.src(['dev/icons/*.svg']) // 【A】のパスを指定
.pipe(iconfont({
startUnicode: 0xF001,
fontName: 'iconfont',
formats: ['ttf', 'eot', 'woff', 'svg'],
appendCodepoints:false,
normalize: true,
fontHeight: 500,
timestamp: runTimestamp
}))
.on('glyphs', function(glyphs) {
gulp.src('dev/icons/templates/iconfont.css') // 【B】のパスを指定
.pipe(consolidate('lodash', {
glyphs: glyphs.map(function(glyph) {
return { fileName: glyph.name, codePoint: glyph.unicode[0].charCodeAt(0).toString(16).toUpperCase() };
}),
fontName: 'iconfont',
fontPath: '../fonts/',
cssClass: 'icon'
}))
.pipe(gulp.dest('dev/css/')); // 【D】のパスを指定
})
.pipe(gulp.dest('dev/fonts')); // 【C】のパスを指定
});
