CSS Modules 支持使用變量,不過需要安裝 PostCSS 和?[postcss-modules-values](https://github.com/css-modules/postcss-modules-values)。
~~~
$ npm install --save postcss-loader postcss-modules-values
~~~
把`postcss-loader`加入[`webpack.config.js`](https://github.com/ruanyf/css-modules-demos/blob/master/demo06/webpack.config.js)。
~~~
var values = require('postcss-modules-values');
module.exports = {
entry: __dirname + '/index.js',
output: {
publicPath: '/',
filename: './bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader?modules!postcss-loader"
},
]
},
postcss: [
values
]
};
~~~
接著,在[`colors.css`](https://github.com/ruanyf/css-modules-demos/blob/master/demo06/components/colors.css)里面定義變量。
~~~
@value blue: #0c77f8;
@value red: #ff0000;
@value green: #aaf200;
~~~
[`App.css`](https://github.com/ruanyf/css-modules-demos/tree/master/demo06/components)可以引用這些變量。
~~~
@value colors: "./colors.css";
@value blue, red, green from colors;
.title {
color: red;
background-color: blue;
}
~~~
運行這個示例。
~~~
$ npm run demo06
~~~
打開`http://localhost:8080`,會[看到](http://ruanyf.github.io/css-modules-demos/demo06/)藍色的背景上有一個紅色的`h1`。