css - 导入全局 css 自定义变量

标签 css webpack postcss postcss-import

我正在尝试将 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"
    })
  ]
};

最佳答案

解决方法: postcss-import 插件必须放在第一位,但是 Postcss-loader 的插件不会像 webpack 加载程序那样以相反的顺序出现。

这修复了它:

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

   ]
}

关于css - 导入全局 css 自定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657521/

相关文章:

css - CSS 翻转的 Internet Explorer 8 问题

javascript - 从react native init 一步步React native web

html - Bootstrap 模式中的图像问题

javascript - 水平滚动导航栏无法正常工作

javascript - 为什么在对同一变量使用 'hidden' 和 'button' 输入时得到 2 个相等的 html GET 参数?

创建 react 应用程序构建错误 "Expected a pseudo-class or pseudo-element."

css - 同步使用自动前缀

webpack - 为什么 hot-update.json 文件挤满了我的项目目录

javascript - Polymer 3 + webpack + babel Class constructor PolymerElement 不能调用没有 'new'

css - PostCSS 和 Webpack 配置