LoginSignup
14
8

More than 5 years have passed since last update.

PostCSSで別ファイルをimportする際の注意点

Last updated at Posted at 2016-10-31

PostCSS & cssnext環境で別cssファイルで変数を定義してimportして利用しようとして、ハマったので、その注意点を共有します。

TL;DR

  • webpack.config.jsのpostcss()内でpostcss-importを一番最初にrequireする

ハマった環境

webpack.config.js
const cssnext = require('postcss-cssnext')
const cssimport = require('postcss-import')

...

postcss() {
  return [cssnext, cssimport] // ここの順序が問題
},

...
colors.css
:root{
  --background-color: #fff;
}
some-component.css
@import 'path/to/colors.css';

.some-component {
  background-color: var(--background-color);
}

実行結果

variable '--background-color' is undefined and used without a fallback
.some-component {
  background-color: var(--background-color); // colors.cssで定義した変数が展開されていない
}

正しい記述例

webpack.config.js内のpostcss()でpostcss-importを最初にrequireする
参考:
https://github.com/MoOx/postcss-cssnext/blob/master/webpack.config.js#L51-L55
https://github.com/css-modules/css-modules/issues/22

webpack.config.js
const cssnext = require('postcss-cssnext')
const cssimport = require('postcss-import')

...

postcss() {
  return [cssimport, cssnext] // postcss-importを最初にrequireする
},

...

実行結果

.some-component {
  background-color: #fff; // colors.cssで定義した変数が展開されている
}

無事に展開されました🎉
ビルドのプロセスを考えると、たしかにimportの展開を先にしないと上手く展開できないですね。

14
8
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
14
8