2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pugでルート相対パスを使うにはbasedirオプションでルートを指定する

Posted at

Pugをgulpでコンパイルする想定です。

ディレクトリ構成

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?