How to use autoprefixer with ViteJS and React?
Asked Answered
G

3

11

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?

Greenhead answered 9/3, 2022 at 19:28 Comment(0)
F
20

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: {}
  }
}

ℹ️ Below is an example of a configuration file vite.config.ts that includes configuration for postcss.

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

export default defineConfig({
  plugins: [
    react()
  ],
  css: {
    postcss: {
      plugins: [
        autoprefixer({}) // add options if needed
      ],
    }
  }
})

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

Fernandes answered 10/3, 2022 at 10:6 Comment(5)
I created the react project using npm create vite but the solution is not working.Connection
Still it's not working. I've created a new question. #73648225 would be great if you can have a look..Connection
Hey! I think this is not a solution, Vite is an alternative to create-react-app so there should be a way to use autoprefixer with it instead of changing the project generator.Pomfret
the question explicitly says they want to use autoprefixer with Vite and React. So suggesting changing the project generator to CRA is the same as explaining how to add autoprefixer to Vue CLI and telling them to use Vue instead.Pomfret
This answer is confusing, the question is specifically about Vite except you keep pointing to create react app. "If it doesn't work, you should check which version of create-react-app you are using". OP isn't using CRA, OP is using viteRetrospection
P
5

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
      ],
    }
  },
  ...
});
Pomfret answered 13/9, 2022 at 14:30 Comment(0)
C
0

Install postcss and autoprefixer with:
npm i autoprefixer -D
npm i postcss -D
then config vite:

import { defineConfig } from "vite";
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
import react from '@vitejs/plugin-react'
import autoprefixer from "autoprefixer";

export default defineConfig({
  plugins: [react(), cssInjectedByJsPlugin()],
  css: {
    postcss: {
      plugins: [autoprefixer],
    },
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: undefined,
      },
    },
  },
});

Coulter answered 14/10, 2022 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.