Search code examples
cssreactjsnestedcreate-react-apppostcss

ampersand postcss-nested not working in create-react-app


Ampersand doesn't work in styles (postcss)

package npm i --dev autoprefixer postcss-nested postcss-cli npm-run-all

commands

"scripts": {
    "start": "npm-run-all -p watch:css start-js",
    "build": "npm-run-all build:css build-js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "build:css": "postcss src/styles/main.css -o src/index.css",
    "watch:css": "postcss src/styles/main.css -o src/index.css -w",
    "start-js": "react-scripts start",
    "build-js": "react-scripts build"
}

postcss.config.js in the root

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

code:

  • index.css
.App {
    background-color: #ffffff;

    &-header {
      background-color: yellow;
    }
}
  • App.js
<div className="App">
    <header className="App-header">test</header>
</div>

why ampersand in code doesn't work?


Solution

  • When using CRA, you need to write npm eject and only then write changes in the config that appears.

    If you don't want to get all the configs when you write npm eject, then use CRACO - it allows you to create a file for configs separately