LoginSignup
38
32

More than 5 years have passed since last update.

Webpack4 + Vue.js + Pug + Sass

Last updated at Posted at 2018-07-12

webpack4でvue.js + pug + sass 環境つくろうとしてハマったのでメモ

やりたかったこと

単純に .vuetemplatepug で、
stylesass(scss) で書きたかっただけ。

sass(scss)は特に問題なかったけど、
templateで lang="pug" を指定するとエラーが出て先に進めなかった。

ググって出てくる記事のほとんどは、
webpackのバージョンが3以前だったり、
特に設定いらないと書かれていたりで参考にならず。。

答えは vue-loaderの webpack.config.js 設定

今回の環境構築でインストールした vue-cli のバージョンが 2.9.6vue-loader のバージョンが 15.2.4 だった。

vue-loaderのサイトに Migrating from v14 と書かれたページを発見。

そこの template に関する記載箇所には

v14 and below uses consolidate to compile <template lang="xxx">. v15 now applies preprocessing for them using webpack loaders instead.

Note that some template loaders such as pug-loader exports a compiled templating function instead of plain HTML. In order to pass the correct content to Vue's template compiler, you must use a loader that outputs plain HTML instead. For example, to support <template lang="pug">, you can use pug-plain-loader:

と書かれていて、ざっくり理解した感じだとプレーンなHTMLを渡すのに、 今まで使っていた pug-loader ではダメで、 pug-plain-loader を使いましょう。ということみたい。

なので

bash
$ npm i -D pug-plain-loader

して

webpack.confg.js
{
  module: {
    rules: [
      {
        test: /\.pug$/,
        loader: 'pug-plain-loader'
      }
    ]
  }
}

でいけました。

なお、

If you also intend to use it to import .pug files as HTML strings in JavaScript, you will need to chain raw-loader after the preprocessing loader. Note however adding raw-loader would break the usage in Vue components, so you need to have two rules, one of them targeting Vue files using a resourceQuery, the other one (fallback) targeting JavaScript imports:

とあり、JavaScript内にHTML文字列として .pug をインポートしたい場合は raw-loader を使う必要があるらしいんだけど、そのまま突っ込むと Vueコンポーネントの処理を止めちゃうそうなので設定を分けていれましょう。とのこと。

bash
$ npm i -D raw-loader

して

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

とすればいいらしい。

英語苦手なんでざっくり理解なんだけどとりあえず解決。

解釈間違ってたらご指摘いただけると嬉しいです(>人<)

38
32
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
38
32