6

我正在尝试将 webpack 与 postcss 一起使用来导入包含我的 css 自定义变量的 theme-variables.css 文件。

//theme-variables.css
:root {
    --babyBlue: blue;
}

基本上我希望任何导入主题变量的 css 都能够访问这些 css 自定义属性并使用 postcss-css-variables 解析为静态值。

//style.css
@import "./theme-variable.css";

div {
    display: flex;
    color: var(--babyBlue);
}

变成

//main.css
div {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    color: blue;
}

但是我不断收到 webpack 错误variable --babyBlue is undefined and used without a fallback

main.js 最终看起来像这样:

:root {
    --babyBlue: blue;
}
div {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    color: undefined;
}

这是我的 webpack(index.js 需要 styles.js):

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: { main: "./src/index.js" },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: { importLoaders: 1 }
          },
          {
            loader: "postcss-loader",
            options: {
              ident: "postcss",
              plugins: loader => [
                require("postcss-css-variables")(),
                require("postcss-cssnext")(),
                require("autoprefixer")(),
                require("postcss-import")()
              ]
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};
4

1 回答 1

3

解决方案:postcss-import 插件必须先出现但是 Postcss-loader 的插件不会像 webpack loader 那样以相反的顺序排列。

这修复了它:

loader: "postcss-loader",
options: {
   ident: "postcss",
   plugins: loader => [
      require("postcss-import")()
      require("postcss-css-variables")(),
      require("postcss-cssnext")(),
      require("autoprefixer")(),

   ]
}
于 2018-12-06T19:05:46.620 回答