Thanooshan
Thanooshan

Reputation: 666

How to add autoprefixer with vite + react project

Hi I created the react app using npm create vite and I tried to integrate autoprefixer but it's not working.

vite.config.js

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

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

package.json

  "devDependencies": {
    "@types/react": "^18.0.17",
    "@types/react-dom": "^18.0.6",
    "@vitejs/plugin-react": "^2.1.0",
    "autoprefixer": "^10.4.8",
    "postcss": "^8.4.16",
    "sass": "^1.54.9",
    "vite": "^3.1.0"
  },
  "browserslist": [ "last 2 versions", "not dead" ] 

I tried creating a postcss.config.js and it didn't worked either.

postcss.config.js

import autoprefixer from 'autoprefixer';

export const plugins = {
    plugins: [autoprefixer()],
};

Would be great if anyone can help me!

Upvotes: 6

Views: 6987

Answers (1)

David Abell
David Abell

Reputation: 121

Vite appears to use postcss-load-config for its configuration.

If the project contains valid PostCSS config (any format supported by postcss load-config, e.g. postcss.config.js), it will be automatically applied to all imported CSS. https://vitejs.dev/guide/features.html#postcss

I solved this with .postcssrc.json and a browserslist root key in package.json.

First install autoprefixer npm install -D autoprefixer

postcss and postcss-load-config are included with vite

No additional config needed in vite.config.js, just the default:

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

export default defineConfig({
    plugins: [react()],
});

.postcssrc.json

{
  "map": true,
  "plugins": {
    "autoprefixer": {}
  }
}

Set up browserslist with one of the recommended options

package.json

{
  ...
  "devDependencies": {
    ...
    "autoprefixer": "^10.4.12",
  },
  "browserslist": [
    "defaults"
  ]
}

Result:

index.css

:root {
 ...
  text-size-adjust: 100%;
}

Compiles to:

:root {
  ...
  -webkit-text-size-adjust: 100%;
  -moz-text-size-adjust: 100%;
  text-size-adjust: 100%;
}

Upvotes: 11

Related Questions