Laravel Elixirで .vue ファイルのCSSにPostCSSを適用する


前提

Laravel 5.3
Webpack 2.1.0-beta.22
Vue.js 2.2.4
PostCss 5.2.16

完成図

https://github.com/noboru-i/laravel-sample/commit/a77de030829f4135a6437f27209f709c4884faf2 が今回分の差分です。

Example.vue などの.vueファイル内に記載したscopedなCSSに対しても、PostCSSが適用されるようになります。

<style scoped>
@import "../../postcss/variables";
.panel {
  & .panel-body {
    font-size: 40px;
    color: var(--mainColor);
  }
}
</style>

出力結果

手順

postcssなどの必要なnode moduleを追加します。
yarnを利用していたので、下記のように実行していきました。

yarn add postcss -D
yarn add postcss-import -D
yarn add postcss-cssnext -D
yarn add postcss-discard-empty -D

すると、package.jsonとyarn.lockが変更されます。
https://github.com/noboru-i/laravel-sample/commit/a77de030829f4135a6437f27209f709c4884faf2#diff-b9cfc7f2cdf78a7f4b91a753d10865a2

次に、プロジェクト直下に webpack.config.js というファイルを新規に作成します。
https://github.com/noboru-i/laravel-sample/commit/a77de030829f4135a6437f27209f709c4884faf2#diff-11e9f7f953edc64ba14b0cc350ae7b9d

module.exports = {
  vue: {
    postcss: function(webpack) {
      return [
        require('postcss-import'),
        require('postcss-cssnext'),
        require('postcss-discard-empty')
      ];
    }
  }
};

これだけで、最初に書いたようなCSSをPostCSSを適用した形で出力してくれるようになります。
- @import による他ファイルの読み込み
- cssnext内の postcss-nesting による、ネストされたCSSの適用
- cssnext内の postcss-custom-properties による、varの解釈

その他、postcssのプラグインであれば、同じようにyarnによるインストール -> webpack.config.jsへの追加によって、追加してくことが出来るかと思います。

感想

.vueファイルによるコンポーネント単位のCSS適用は、管理が楽になりそうなので良さげ。
その中でもPostCSSが使えれば、かんたんに書けたり、autoprefixerによる互換性の担保だったりがかんたんに出来そう。

ただ、Laravel 5.4でElixirからMixになったんですよね。。。