LoginSignup
1
3

More than 5 years have passed since last update.

Browsersync で SSI を使う (rewriteRules編)

Last updated at Posted at 2018-09-20

Browsersync で SSI したい

Browsersync で SSI を使いたい場合、ちょっと調べると browsersync-ssi などのパッケージを middleware として使う方法がよく出てきます。

ただ、すでに他の middleware を導入しており、バッティングしてすんなり動かない……というケースがありましたので、別の方法で SSI を動かしてみたメモです。

rewriteRules を使う

Browsersync の rewriteRules オプションで、html の中身を自由に書き換えられる模様。
ということで SSI の仕組みをそこに埋め込みます。

ざっくりこんな感じ

const browserSync = require('browser-sync');
const fs = require('fs');
const path = require('path');

browserSync.init({
    server: 'public',
    files: 'public/**/*',
    rewriteRules: [
        {
            match: /<!--#include virtual="(.+)" -->/g,
            fn: function (req, res, match, filename) {
                const filePath = path.join(__dirname, 'public', filename);
                if (! fs.existsSync(filePath)) {
                    return `<span style="color: red">${filename} could not be found</span>`;
                }
                return fs.readFileSync(filePath);
            }
        }
    ],
});

ゴリゴリ感はありますが、動いた。

参考

1
3
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
1
3