LoginSignup
2
3

More than 5 years have passed since last update.

Webpack + PostCSSで変数を使う

Last updated at Posted at 2017-09-09

概要

postcss-simple-vars を使って、 vue-cli を使って初期化したプロジェクトのCSSで変数を使えるようにする。

※追記 こんなことしなくて良かった。下記のように定義できる。

:root {
  --color-primary: #d1fb3c;
  --color-secondly: #d1;
  --color-foundation: #d1;
}

.test {
  background: var(--color-primary);
}

※さらに追記

上記の変数表記は、ただW3Cが提唱している新しいCSSの仕様に従っているだけだった。
Chromiumでは実装済みのため、変数が適用されていると勘違いしてしまった。

postcss-css-variables をインストールすると、この記法が使えるらしい。

参考
https://blog.mismithportfolio.com/web/20161001postcssvar

プロジェクトの初期化

vue init webpack vars_test
cd vars_test
yarn install
yarn start

postcss-simple-vars 導入

まずはパッケージを追加します。

yarn add postcss-simple-vars

次に、 .postcssrc.js を編集してプラグインを有効化します。

.postcssrc.js
// https://github.com/michael-ciniawsky/postcss-load-config

module.exports = {
  "plugins": {

    // [追加]
    "postcss-simple-vars": {
      variables: require('./src/variables.css.js')
    },
    // [/追加]

    // to edit target browsers: use "browserslist" field in package.json
    "autoprefixer": {
      "browsers": "last 2 versions"
    }
  }
}

最後に、変数を記述します。

src/variables.css.js
module.exports = {
  info: '#40cec0',
}

これでもう一度 yarn start すれば、変数が有効になっています。

確認

src/App.vue
<style>
body {
  background: $info;
}
</style>

うまくいけば、背景が青くなるでしょう。

所感

Webpackのプラグイン周りは、色んな書き方があって戸惑う。

postcss.config.js の記法だとこうなる。ううむ。

postcss.config.js
module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-simple-vars')({
      variables: require('./src/css/variables.css.js')
    }),
  ]
}
2
3
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
3