Search code examples
csstypescriptwebpackpostcsspostcss-loader

Webpack - Postcss nesting not working used as suggested


I have this simple css that uses a nested rule.

.root {
  background: var(--color-accent);
  padding: 0.8rem 1.5rem;
  color: var(--color-white);
  text-decoration: none;
  &:hover {
    background: var(--color-purple);
  }
}

I am using postcss-loaderin Webpack as loader.

  {
    test: /\.css$/i,
    use: ["style-loader", "css-loader", "postcss-loader"],
  },

And this is my postcss.config.js file. It is the same as the code used in https://github.com/postcss/postcss-nested#usage

module.exports = {
  plugins: ["autoprefixer", "postcss-nested"],
};

The css file is loaded, but the nested rule is stil as it is. The browser does not recognize it.

What to do to achive the following?

.root {
  background: var(--color-accent);
  padding: 0.8rem 1.5rem;
  color: var(--color-white);
  text-decoration: none;
}


.root:hover {
  background: var(--color-purple);
}

CSS variables are defined in the genereated css (colors works). The postcss.config.js is file loaded too.

A screenshoot of the nested css in Chrome.

enter image description here

Update

I set up a similar project on Codesandbox.

https://codesandbox.io/s/zealous-tree-chz7y3

Post-css-nesting works neither.

module.exports = () => ({
    plugins: [
        require("postcss-preset-env")({
            stage: 3,
            features: {
                "color-mod-function": { unresolved: "warn" },
                "nesting-rules": true,

                "custom-properties": {
                    preserve: false,
                },
            },
        }),
    ],
});

Solution

  • You're using create-react-app. I'm afraid it didn't support postcss.config.js yet, as seen in this thread.

    I think you'll need to refactor your code to some extent. For example, you could try using craco to override CRA configuration.