pugのインストール
pugという名前は聞いたことがあったのですが、使っていませんでした。
sassはコンパイルしてcssを書き出すものですが、pugはコンパイルしてhtmlを書き出すものといった感じです。
Emmetを利用していたので、すでにtmlの書き出しに関しては便利になったんですが、pugはヘッダーやフッターなどの共通部分をインクルードすることができるみたいなので、大規模サイト構築の場合に便利そうです。
環境設定が大変なのかなと思ったのですが、下記URLを参照してインストールしたら一瞬でインストール完了しました。
【Pug】ゴリラでもわかるJade改めPug入門
gulpのインストール
今回は、一緒にgulpも使うことにしました。
gulpも便利ということは耳にしていたのですが、設定が面倒そうだったので利用していませんでした。
下記サイトを参考にインストールしました。
絶対つまずかないGulp 4入門(2019年版)インストールとSassを使うまでの手順
インストールとコンパイルまではできたのですが、Watchがうまく動かなかったので他のサイトを参考にしました。
gulp+pug+scss+autoprefixerのコンパイルが突然できなくなったので、gulp4に移行した話
gulp4だとgulp3と書き方が違うみたいです。
基本的にはこれで動いたのですが、PC用とSP用で分けてhtmlやcssを書く時のために下記のようにgulpfile.jsを作成しました。
gulpfile.js
var gulp = require("gulp"); var sass = require("gulp-sass"); var plumber = require("gulp-plumber"); var notify = require("gulp-notify"); var pug = require("gulp-pug"); var autoprefixer = require('gulp-autoprefixer'); //sassをcssに変換してautoprefixer gulp.task('sass', function(done) { gulp.src("./build/scss/**/*scss") .pipe(plumber({ errorHandler: notify.onError("Error: <%= error.message %>") })) .pipe(sass({outputStyle: 'expanded'})) .pipe(autoprefixer({browsers: ["last 3 versions", "ie >= 9", "Android >= 4","ios_saf >= 8"]})) .pipe(gulp.dest("./build/css")) done(); }); gulp.task('sasssp', function(done) { gulp.src("./build/sp/scss/**/*scss") .pipe(plumber({ errorHandler: notify.onError("Error: <%= error.message %>") })) .pipe(sass({outputStyle: 'expanded'})) .pipe(autoprefixer({browsers: ["last 3 versions", "ie >= 9", "Android >= 4","ios_saf >= 8"]})) .pipe(gulp.dest("./build/sp/css")) done(); }); //pugをhtmlに変換 gulp.task('pug', function(done) { var option = { pretty: true } gulp.src(['./build/pug/*.pug', '!./build/pug/_*.pug']) .pipe(plumber({ errorHandler: notify.onError("Error: <%= error.message %>") })) .pipe(pug(option)) .pipe(gulp.dest("./build/")) done(); }); //pugをhtmlに変換 gulp.task('pugsp', function(done) { var option = { pretty: true } gulp.src(['./build/sp/pug/*.pug', '!./build/sp/pug/_*.pug']) .pipe(plumber({ errorHandler: notify.onError("Error: <%= error.message %>") })) .pipe(pug(option)) .pipe(gulp.dest("./build/sp/")) done(); }); gulp.task('default', gulp.series('sass', 'pug', 'sasssp', 'pugsp')); // taskの名前はdefaultにしましたが、何でも大丈夫 //sassとpugの監視をして変換処理させる gulp.watch(['./build/scss/**'], gulp.task('sass')); gulp.watch(['./build/sp/scss/**'], gulp.task('sasssp')); gulp.watch(['./build/pug/**'], gulp.task('pug')); gulp.watch(['./build/sp/pug/**'], gulp.task('pugsp'));
これで便利になりましたが、慣れるまで少々時間がかかりそうです。