0
0

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 3 years have passed since last update.

[Webpack].pug ファイルをJavascript のHTMLテンプレートとして使用する方法

Posted at

起こったこと

Webpack 上で.pug ファイルでpug記法のHTMLを管理したい。が

(Webpack でVue.jsの SFC(Single File Components) で pug記法を使用する方法はよくあったが)
直接pug ファイルでpug記法のHTMLを管理する方法がなかったのでメモ。

環境

Webpack 4(RailsWebpacker)

問題

普通にpug の renderFile でファイル読み込みすれば?
と思ったが、
node.js のモジュールのfs に依存しているようで fs.readfilesync is not function で上手くいかなかったため、
別の方法でファイルを読み込み、
機能するrender メソッドのみ使うことにした。

pug関連にはいくつかloader があるが
想定する動作をしなかった。

As mentioned earlier, the purpose of using Pug templates is to generate static HTML pages. After Webpack v4, all loading will go to module.rules, so we need to add the appropriate loader.

Unfortunately, Pug has three loaders: pug-loader, pug-html-loader, pug-plain-loader, which one should we use?

Frankly speaking, this problem bothered me for about half a day. The specific process will not start, let's talk about the final plan:

pug-plain-loader is a minimalist loader developed by the author of Vue to use Pug templates in Vue. Its function is to convert pug into a pure HTML string. Does not meet our needs, rule out.
pug-html-loader is similar, but also excluded.
The pug-loader converts pug into a template function, and how to use it is handed over to the next level loader. So we can add external variables during the compilation process and change the compiled content. Obviously, this is exactly what we need.

解決法

webpack のraw-loader でpug ファイル内容をString で取得し
pug のrender メソッドで
処理する。

webpack-config.js
module.exports = {
  test: /\.pug$/,
  oneOf: [
    // this applies to pug imports inside JavaScript
    {
      exclude: /\.vue$/,
      use: ['raw-loader']
    },
    // this applies to <template lang="pug"> in Vue components
    {
      use: ['pug-plain-loader']
    }
  ]
}

module.js
import pug from 'pug'
import tmpl from '../tmpl.pug'

const html = pug.render(tmpl, {data: 111})

もっとよい方法はあるだろうが
とりあえず動いた。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?