Postcss-loader警告"变量未定义,在没有回退的情况下使用",用于包含两个CSS文件的we



在 webpack 条目文件索引中.js我只是导入了 2 个 CSS 文件 a.css 和 b.css但由于 b.css 看不到来自 a.css:WARNING in b.css... variable --textColor is undefined and used without a fallback的变量而不起作用。我应该如何更改 webpack.config.js 才能让它工作?我知道我可以直接在 a 中导入 b.css.css但这是一个简单的例子,我的项目要复杂得多,有几十个 CSS 文件,我不想更改它的内容。

// webpack.config.js
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = (env, options) => {
return {
entry : 'index.js',
mode : 'development',
output : {
path : '/public',
},
plugins : [
new MiniCssExtractPlugin(),
],
module : {
rules : [
{
test : /.css$/,
use : [
{
loader : MiniCssExtractPlugin.loader,
},
{
loader : 'css-loader',
},
{
loader : 'postcss-loader',
options : {
plugins: [
require('postcss-css-variables')(),
],
},
},
],
},
],
},
};
}
// index.js
import 'a.css';
import 'b.css';
// a.css
:root {
--textColor: red
}
// b.css
body {
color: var(--textColor);
}

首先,@import很快就会被弃用。使用@use和@forward,因此值得一读。


https://sass-lang.com/documentation/at-rules/use https://sass-lang.com/documentation/at-rules/forward

postcss-css-variables如果你需要支持旧版浏览器(ie11(,你只需要postcss-css-variabless。 否则,只需按原样使用 css-var。如果您需要遗留支持,我真的建议您构建双(对于现代和带有转译的 css vars 的(。

这是@import的旧配置

{
// snippet from
// https://github.com/unic/darvin-webpack-boilerplate/blob/master/webpack/settings/style-legacy/index.js#L29
loader: 'postcss-loader',
options: {
plugins: () => [
autoprefixer({
grid: 'autoplace',
flexbox: 'no-2009'
}),
require('postcss-css-variables')({ preserve : false, preserveAtRulesOrder: true })
],
sourceMap: false,
},
},

最新更新