How to use autoprefixer with ViteJS and React?

Viewed 2544

I'm using React with ViteJS and SASS, but i have a problem. It seems there is not autoprefixer for CSS/SCSS when i will build the project.

How to add an auto-prefixer with ViteJS and SASS?

2 Answers

If you created your app with Create React App then autoprefixer is used automatically and you might just need to set "browserslist": [ "defaults" ] in your package.json.

Else, try to add postcss and autoprefixer: yarn add -D postcss@latest autoprefixer@latest

then add a file postcss.config.js on your root project directory:

module.exports = {
  plugins: {
    autoprefixer: {}
  }
}

ℹ️ You can find bellow an example of vite.config.ts for a new project without a postcss config file.

import { defineConfig } from "vite"
import react from '@vitejs/plugin-react'
import autoprefixer from 'autoprefixer'

export default defineConfig({
  plugins: [
    react()
  ],
  css: {
    postcss: {
      plugins: [
        autoprefixer: {}
      ],
    }
  }
})

If it doesn't work, you should check which version of create-react-app you are using. eg., create-react-app v5 usepostcss v8.

To update your build tooling as the doc say, you can run npm install react-scripts@latest.

And if it still doesn't work please provide a reproducible project.

First, you have to install autoprefixer:

npm i autoprefixer -D

after that, you have to go to your vite.config.ts and add it there:

import autoprefixer from 'autoprefixer';

export default defineConfig({
  plugins: [react()],
  css: {
    ...
    postcss: {
      plugins: [
          autoprefixer
      ],
    }
  },
  ...
});
Related