loading

HCJmemory

Pugでルート相対パスを使う

Pugでルート相対パスを使えるようにします。
gulpでPugをコンパイルします。

目次

  1. オプションの追加
  2. 実際に書いてみる
  3. 参考

オプションの追加

このようなディレクトリ構成とします。

root/
  ├ dest/
  │  └ index.html
  ├ src/
  │  ├ _include/
  │  │  ├ _header.pug
  │  │  └ _footer.pug
  │  └ index.pug
  └ gulpfile.js

Pugのbasedirオプションに、ルートとして設定したいディレクトリを指定します。今回はsrcディレクトリをルートにします。

gulpfile.js
const { src, dest } = require('gulp')
const pug = require('gulp-pug')
const path = require('path')

const pugCompile = () => (
  src('./src/**/!(_)*.pug')
  .pipe(pug({
    basedir: path.resolve(__dirname, 'src')
  }))
  .pipe(dest('./dest/'))
)

exports.default = pugCompile

実際に書いてみる

Pugを書いてみましょう。

_header.pug
header
  h1 header.
_footer.pug
footer
  p footer.
index.pug
doctype html
html(lang='ja')
  head
    title document
  body
    include /_include/_header.pug
    include /_include/_footer.pug

コンパイルして、以下のようなHTMLが出力されれば成功です。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <title>document</title>
</head>
<body>
  <header>
    <h1>header.</h1>
  </header>
  <footer>
    <p>footer.</p>
  </footer>
</body>
</html>

参考