How to add autoprefixer with vite + react project
Asked Answered
S

1

5

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!

Sterner answered 8/9, 2022 at 10:39 Comment(2)
Can you say which node version you are on ?Menado
@Menado node: v18.7.0, npm: 8.15.0Sterner
T
11

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%;
}
Trash answered 7/10, 2022 at 11:23 Comment(3)
took 2 hrs to figure this browserslist thingChangeful
Why is the browserList defaults necessary?Cindelyn
After pulling my hair out of frustration, "browserslist": ["cover 99.5%"] worked. P.S. You can run npx browserlist to see which browsers were supported by the querySeumas

© 2022 - 2024 — McMap. All rights reserved.