LoginSignup
9
12

More than 5 years have passed since last update.

大規模サイト構築で重くなったpugのプロジェクトを高速化する。

Last updated at Posted at 2017-03-28

サイトの画面構成がそれなりの規模感になってくると pug のビルドにも時間がかかるようになってきます。

pug で全体を毎回ビルドする設定をしていると、 public 配下をwatch する browserSync が無限にリロードを重ねるようになり、ブラウザがぶっ壊れます。

変更のあったpugファイルのみ変更反映すればいいんですが、依存関係ぐちゃぐちゃのpug構成内では、そううまいこと行きません。

pug コンパイルタスクの完了に合わせて browserSync のリロードとか書ければいいんですがビルドに 5s とかかかるようになってくると流石に待てないですね。

というわけで browserSync に mddleware を刺して動的に pug ファイルをコンパイルするアレです。

const fs = require("fs")
const path = require("path")
const url = require("url")
const pug = require("pug")

const pugMiddleWare = (req, res, next) => {

    const basedir = process.cwd();
    const requestPath = getPugTemplatePath(basedir,req)

    if (path.parse(requestPath).ext !== ".html") {
        return next();
    }
    const pugPath = requestPath.replace('.html', '.pug');

    try{
        console.log("[BS] try to file "+ pugPath)
        fs.statSync(pugPath)
        const content = pug.renderFile(pugPath, {
            locals:{},
            pretty: true,
            basedir,
            compileDebug: true,
            doctype: "html"
        });
        res.end(new Buffer(content));
        next();
    }catch (e){
        console.log(e)
        return next();
    }
}

const getPugTemplatePath = (baseDir,req)=>{
    const requestPath = url.parse(req.url).pathname;
    const suffix = path.parse(requestPath).ext ? "": "index.html"
    return path.join(baseDir,"assets/pug",requestPath,suffix);
}

gulp で使うときにはこんな感じで

gulp.task("server",()=> {
    browserSync({
        server:{
            middleware: [pugMiddleWare],
            baseDir:"public",
            index: "index.html",
            open: false
        }
    })

    return gulp.watch(process.cwd()+"/**/*", () => {
        setTimeout(function(){
            browserSync.reload();
        },500);
    });
});

9
12
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
9
12