3
4

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.

Vue-CLI4系でPostCSSプラグインを導入する方法

3
Last updated at Posted at 2019-11-17

はじめに

Vue-CLI4系はpostcssがデフォルトで入っており、package.jsonのPostCSSのプラグインへ今回使用するライブラリ(postcss-simple-vars,postcss-easy-import)を追加するだけで使えるようになると思っていたのですが、うまくいかずハマってしまいました。。。

開発メモとしてVue-CLI4系でPostCSSプラグインを導入する方法まとめましたので、同じようにつまってしまった方はご参考にしていただけると嬉しいです。

1. Vueファイルに直接PostCSSを書く場合

Vueファイルに直接PostCSSを書く場合は、拡張したいプラグインのライブラリ(今回はpostcss-simple-vars、postcss-easy-import)をインストールし、package.jsonのPostCSSのプラグインへ対象ライブラリを追加するだけでOKです。

コンソール
$ npm install --save-dev postcss-easy-import postcss-simple-vars
package.json
  "postcss": {
    "plugins": {
      // プロジェクト作成時にデフォルトで入ってるプラグイン
      "autoprefixer": {},
      // 今回追加したいプラグイン
      "postcss-easy-import": {},
      "postcss-simple-vars": {}
    }
sample.vue
<style lang="postcss" scoped>
$white_murky: #fafafa;

.header {
  background-color: $white_murky;
}
</style>

2. Vueファイルに外部PostCSSファイルを読み込む場合

Vueファイルにimportを使用して、外部PostCSSファイルを読み込む場合は、上記のやり方ではうまくいきませんでした。

Vueファイルに外部PostCSSファイルを読み込む場合とはどのような場合かといいますと、以下のようなケースです。

sample.vue
<style lang="postcss" scoped>
// importしたいcssファイル
@import './colors.css'


.header {
  background-color: $white_murky;
}
</style>
colors.css
<style lang="postcss" scoped>
$white_murky: #fafafa;
</style>

上記1のような実装方法だと、シンタックスエラーとなり、うまくいきませんでした。

公式サイトをみると、postcss.config.js使えるようなので、上記1のpackage.jsonをいじって実装するのをあきらめ、postcss.config.jsへPostCSSのプラグインを追加することにしました。

postcss.config.js
const postcssEasyImport = require('postcss-easy-import')
const postcssSimpleVars = require('postcss-simple-vars')

// 使用プラグイン
const initPlugin = [
  postcssEasyImport({}),
  postcssSimpleVars({})
]

// 実行
module.exports = {
  plugins: initPlugin
}

こうすることで、無事外部ファイルのcss(colors.css)を読み込むことができました♪

上記1のpackage.jsonをいじるやり方でも問題なく外部PostCSSファイルを読み込むようにできるのかもしれないのですが、PostCSSファイルのプラグインのオプションとかを使用する場合は実装が特殊になりそうなので、ボクはpostcss.config.jsをいじるやり方のほうが好きです。

ちなみにPostCSSファイルのプラグインのオプション利用する場合は、postcss.config.jsの以下の部分へオブジェクト型でコーディングします。

postcss.config.js
  postcssEasyImport({/* ここにオプションコーディング */}),
  postcssSimpleVars({/* ここにオプションコーディング */})

とはいえ、package.jsonをいじるやり方でも問題なく外部PostCSSファイルを読み込めるようにする方法やPostCSSファイルのプラグインオプションをpackage.jsonへ書く方法について、個人的には気になっててモヤモヤしてるので、もしご存知の方いらっしゃいましたらコメントください><

さいごに

2020年から個人ブログはじめました!

フリーランスエンジニアになって得た知識と経験をもとに、フリーランスエンジニアに関する情報をはじめ、IT技術情報や業界情報、エンジニアライフハック等のコンテンツを配信していく予定です。

まだまだ記事数は少ないのですが、週単位で更新してますので、もしご興味ございましたら、みていただけると嬉しいです。

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?