cssreactjssasspostcsspostcss-loader

Is there an easy way to add PostCSS to a SASS React project?


I have a React project that uses SASS with the following configurations:

{
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "^5.0.1",
    "sass": "^1.70.0"
  }
}

I would like to add PostCSS to remove repetitive/duplicate CSS Rules and optimize the styling files. Admittedly, I do not know much about PostCSS.

I tried adding the following as my postcss.config.js:

// postcss.config.js
module.exports = {
  plugins: [
    require('postcss-import'),
    require('autoprefixer'),
    require('cssnano')({
      preset: 'default',
    }),
  ],
};

and the following command:

npm install --save-dev postcss postcss-cli postcss-import autoprefixer cssnano postcss-loader

However, I do not believe anything happened and duplicate css lines were still there when inspecting in the browser.

Here is a link to my project: qamous.org


Solution

  • Your project was created using the (deprectated) CRA, which means your code is handled by webpack via react-script config. This config already has a loader configured with PostCSS, as you can see here:

    {
      // Options for PostCSS as we reference these options twice
      // Adds vendor prefixing based on your specified browser support in
      // package.json
      loader: require.resolve('postcss-loader'),
      options: {
        postcssOptions: {
          // Necessary for external CSS imports to work
          // https://github.com/facebook/create-react-app/issues/2677
          ident: 'postcss',
          config: false,
          plugins: !useTailwind
            ? [
              'postcss-flexbugs-fixes',
              [
                'postcss-preset-env',
                {
                  autoprefixer: {
                    flexbox: 'no-2009',
                  },
                  stage: 3,
                },
              ],
              // Adds PostCSS Normalize as the reset css with default options,
              // so that it honors browserslist config in package.json
              // which in turn let's users customize the target behavior as per their needs.
              'postcss-normalize',
            ]
          : [
              'tailwindcss',
              'postcss-flexbugs-fixes',
              [
                'postcss-preset-env',
                {
                  autoprefixer: {
                  flexbox: 'no-2009',
                },
                stage: 3,
              },
            ],
          ],
        },
        sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
      },
    },
    

    If you don't intend to get out of CRA and wish to update this config, you can either eject your app, or use a tool such as craco or react-app-rewired to override the config.