ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
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`。