Css autoprefixer не работает

Автопрефиксер — окончательное решение проблемы префиксов в CSS

Автопрефиксер — утилита нового поколения для добавления префиксов к экспериментальным свойствам из CSS 3. Она берёт с Can I Use последние данные о префиксах и популярности браузеров, читает ваш файл стилей, находит свойства и значения, которым действительно нужны префиксы и добавляет их.

Читайте также:  Нет связи с терминалом как настроить

Вы просто пишите обычный CSS:

Автопрефиксер сам заменит нужные (и только нужные) свойства и значения (обратите внимание на -webkit-transform ):

Эта утилита работает во время выкладки сайта на сервера (и на машине программиста во время разработки), так что не заметна для клиентов и не требует какой-то поддержки от браузеров.

Проблема

К сожалению текущие инструменты плохо решают задачу:

  • Писать вереницы свойств руками — очевидно плохое решение. Такой код невозможно читать, легко забыть поправить остальные свойства при редактировании.
  • В Sass и LESS вам нужно самому следить за актуальностью префиксов и копировать примеси из проекта в проект. К тому же примеси могут решить проблему только у свойств, а не у значений (например, calc() ).
  • Compass или Bourbon уже лучше, там список примесей хранится централизовано и его легче держать актуальным (но практика показывает, что обычно в примеси добавляют все префиксы не следя за актуальностью). Проблема значений всё так же не решена.
  • Самая главная проблема Sass и LESS, что вам всё равно нужно постоянно думать «из CSS 3 это свойство или нет?» — и в зависимости от этого использовать примесь или нет. Эту проблему немного решил Stylus — у него синтаксис примесей не отличается от обычных свойств, так что префиксы добавляются невидимо. Впрочем, проблема актуальности и значений всё равно остались.
  • Есть ещё скрипты добавления префиксов прямо в браузере, например Prefix Free, но лучше всего обрабатывать стили на этапе разработки и выкладки, а не повторять обработку каждый раз в браузере клиентов.

Понятно, что языки препроцессоров не позволяют решить проблему полностью, нужен был фундаментально новый инструмент.

Это понимал и разработчик Stylus, TJ Holowaychuk, поэтому он начал разработку препроцессора нового поколения — Rework. Это не отдельный язык, который компилировался в CSS (как Sass или Stylus), а именно препроцессор CSS-дерева:

  • сначала CSS-парсер строил дерево стилей;
  • потом JS-функции меняли это дерево как угодно;
  • в конце новое дерево сохранялось в CSS-файл.
Читайте также:  Где можно починить механическую клавиатуру

В итоге новый инструмент был гораздо гибче — можно было действительно делать с CSS всё что угодно. Поэтому именно Rework лёг в основу Автопрефиксера.

Преимущества

Вам не нужно учить новый язык

Автопрефиксер работает поверх обычного CSS — так что вам не нужно всей командой мигрировать на новый язык. При этом он остаётся совместим с другими языками типа Sass и Stylus — нужно только запустить его после компиляции CSS.

Вам не нужно думать, нужна ли здесь примесь или нет — можно совсем забыть о префиксах. Автопрефиксер сам найдёт, что нужно менять — вы пишите обычный CSS с обычными свойствами и значениями.

Префиксы для значений

Благодаря гибкости Rework Автопрефиксер может добавлять префиксы и для @keyframes , и для значений. Например, в Compass, очень трудно указывать transition -анимацию для свойств из CSS 3, типа — примесями это указать нельзя и приходится перечислять все возможные префиксы для transform .

Всегда актуальные данные

Во-первых, чтобы не зависеть от свободного времени авторов, база данных Автопрефиксера обновляется автоматическими скриптами с Can I Use, так что данные всегда остаются свежими.

Во-вторых, вы указываете те версии браузеры, которые поддерживаете (по умолчанию, как в Гугл, берутся 2 последние версии каждого браузера) — можно указать и по статистике глобального использования, например «больше 1 %».

В итоге в CSS будут только действительно нужные префиксы, файлы будут опрятные и их легко будет смотреть в Веб-инспекторе браузера.

Использование

Ruby on Rails

Для Rails есть гем «autoprefixer-rails» — вам нужно только подключить гем и префиксы будут сами добавляться в ваши CSS-файлы из app/assets/ и lib/assets . Достаточно добавить в Gemfile и дальше писать обычный CSS:

Благодаря гибкости Assets Pipeline, префиксы будут добавлять и к вашим стилям в Sass, и в Stylus. Браузеры можно указать в файле config/autoprefixer.yml :

Можно узнать, какие префиксы будут добавляться с помощью задачи rake autoprefixer:inspect .

Если вы используете Sprockets без Rails (например, вместе с Sinatra), то можно подключить Автопрефиксер к нему:

Можно обрабатывать CSS и без вообще Sprockets:

JavaScript

Для компиляции в node.js можно использовать пакет с npm:

Если же вам нужно обрабатывать CSS в браузере, то можно взять специальную сборку скрипта.

Если вы уже используете Rework, то можете подключить отдельный фильтр Автопрефиксера:

Другое

Автопрефиксер можно интегрировать и с другими языками и системами с помощью отдельного приложения:

Источник

postcss autoprefixer not working #140

Comments

paulrberg commented Apr 10, 2018 •

I have the postcss.config.js file in the root of my project:

I’ve installed the required modules, but the autoprefixer doesn’t work. When I inspect the entities in Chrome, they don’t have the proper complementary prefixes eg -ms-flexbox- along flex .

The text was updated successfully, but these errors were encountered:

stephensauceda commented Apr 18, 2018

I also followed the example provided and was unable to get autoprefixer working. The syntax I ended up using to get it working was:
postcss.config.js

mrxblnx commented May 23, 2018

Works for me (next 6.0.x)

kylemh commented Jun 10, 2018

@stephensauceda’s workaround solved my problems using a few postcss plugins 👍

muhaimincs commented Oct 13, 2018

anything new with next 7?

nagman commented Oct 24, 2018

Since next 7, this code in postcss.config.js doesn’t work anymore:

Also I get a bunch of warnings in the console when building pages in dev mode:

The warning message is You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.

ed-zm commented Oct 25, 2018

I am running into the same issue, any update?

kylemh commented Oct 25, 2018 •

with success on 7@latest in my postcss.config.js

blujedis commented Oct 30, 2018

@kylemh so glad you got to this 4 days b4 I did 🙂 Thx for posting that!

nagman commented Oct 30, 2018

@kylemh Changes nothing for me.

I still have this stack effect in my console, and nothing gets autoprefixed:

blujedis commented Oct 30, 2018

@nagman try to configure your browsers etc. So like

nagman commented Oct 30, 2018

@blujedis Nope. Nothing changed :/

Here’s my postcss.config.js:

And I still got the same two issues:

  1. My console goes freestyle
  2. No autoprefixing in the browser

blujedis commented Oct 30, 2018

@nagman the good news is, it’s just your configuration. What I mean is it’s for sure working here’s a quick test I just did.

Here are two tests, flexbox and linear-gradient. Just ran it.

Here’s my working next.config.js. (including this so you have everything).

. and here’s my postcss.config.js

Again you can adjust your browser settings as you wish the above I think are just the create-react-app defaults.

Maybe duplicate what I have here (without the Typescript) plugin unless you’re using TS and then work from here.

Hope that helps!

kylemh commented Oct 30, 2018

@nagman you’re returning an object with a key of autoprefixer , you need to return an object with a key of plugins that has an object with a key of autoprefixer .

You’re supposed to be returning the entire postcss config — not just your autoprefixer options.

nagman commented Oct 30, 2018

@kylemh Woops, you’re right.
I’ve corrected it:

But still the two same issues.

kylemh commented Oct 30, 2018 •

try copying my config exactly first — context and all. Can you make a reproduction of the issue?

blujedis commented Oct 30, 2018

@nagman question are you importing into one of your app components NOT named _document.js or are your sheets in the /static directory?

If the later I don’t believe they’re getting processed. You’d likely have to modify your config for webpack and push the appropriate loaders/tests etc.

I could be wrong (a bit new to Next) but that’s what I see.

Maybe @kylemh knows more.

nagman commented Oct 31, 2018

@blujedis I’m importing all of my css in my app components, not in the pages.
And I use modular CSS — maybe the reason of the issue?

@kylemh I don’t have your config, you did not provide it.

Here’s my next.config.js:

kylemh commented Oct 31, 2018 •

Delete your importLoaders line. You have 2 loaders at play.

It’d be lovely if some details were changed at this spot of the NextSass README to prevent this situation going forward.

Also, delete postcss loader options — NextCSS will automatically use find-up to grab you postcss.config.js . (Even if you left it, you’ve got the same issue going on there which we referrerd to earlier with the incorrect keys).

Would love if you made a PR to change the NextSass README to save other people from going through this issue! I can see how you ended up in this situation.

nagman commented Nov 1, 2018

@kylemh Thanks! But it only solved one of the two issues.

I’ve removed the importLoaders line, and now my console behaves normally (no errors spaming my screen).

But still nothing autoprefixed in my browser, yet 😢

And when I removed the postcssLoaderOptions , it showed me this error:

Would I need to install this module separately?

blujedis commented Nov 1, 2018

@nagman yes you need to install autoprefixer, as well as any other plugins or whatever you’re using.

For example I’m using postcss-nested which I had to install and then tell next about it.

Next doesn’t ship with every plugin for obvious reasons.

nagman commented Nov 2, 2018

There really is something strange with this. I’ve done everything you said, got no errors in my console, but still zero autoprefixing.

And I’ve installed autoprefixer with: yarn add autoprefixer

kylemh commented Nov 2, 2018 •

Any chance of seeing a reproduction? I’d love to help resolve this for you.

Without seeing what else could be going wrong, I can only suspect that spreading potential context defaults could be the issue, but I don’t think so. Can you change your postcss config to this:

nagman commented Nov 7, 2018

@kylemh Still doesn’t work 😞

kylemh commented Nov 7, 2018

I need a reproduction to help you further. There’s something else going on.

mlzachen commented Nov 16, 2018

This works for me:

  1. Create postcss.config.js in project root.
  2. Add autoprefixer to package.json (yarn add —dev autoprefixer)
  3. Add the following to postcss.config.js:

nagman commented Nov 16, 2018

@m7dev Thanks a lot. It works, at last 🎉

blujedis commented Nov 16, 2018

@nagman glad you’re up but this is pretty much what I indicated here #140 (comment) albeit with a more verbose config.

Sounds like the issue was how postcss config was outputting meaning you expected something the config you had was not supporting rather than anything to do with Next.

radeno commented Jan 4, 2019

@nagman you can use package.json property browserlist
Eg:

it is automatically used in autoprefixer but what is more important also into babel so you can enhance compatibility not just for styles, but also for scripts

mccoyrjm commented Aug 14, 2019

FYI, @radeno’s tip is the more suggested route. Using this config:

After going with the package.json option, I was able to use this config with success!

YasinChan commented Sep 3, 2019

Within postcss.config.js you should define

What’s more ,there is a better way to fix

kelvinlouis commented Oct 22, 2019

If you are experiencing issues regarding CSS Grid, make sure you add cssGrid: true to your postcss.config.js:

khatkarr commented Oct 24, 2019

Has anybody tried autoprefixer with css-in-js. Pls share the config. I am using current version of Next js version 9 I tried all the config in this thread but none works in Nextjs 9.
I shared my issue on Spectrum.
https://spectrum.chat/next-js/general/trying-to-add-postcss-autoprefixer-for-css-in-js-styles

leinov commented Jul 18, 2020

  1. Create postcss.config.js in project root.
  2. Add autoprefixer to package.json (yarn add —dev autoprefixer)
  3. Add the following to postcss.config.js:

kirincc commented Sep 9, 2020

In my case, I found out that if you set postcss-loader’s plugins in webpack.config.js, it will overrides the plugins setting in postcss.config.js.
Just keep one of them.

Coinhunter commented Sep 21, 2020

Not sure if this will end up being the correct thread, but I’m having a very similar problem where I’m not getting any autoprefixes to work with my CSSModules. For some reason it won’t process those css files. I’ve been over the docs, but I’m likely missing something. I’ve tried removing all of the postcss config to see if the default would pick up my Component.module.css files, but it does not prefix those automatically. I’m just using CSS, so I assume I’d need to use next/withCSS in some way, which I have not when it hasn’t been picked up. However, the documentation is not clear on how to get those files to be autoprefixed.

My current (works in chrome without prefixes) config:

Would it help to switch to sass instead? Perhaps then that loader would take care of the prefixing?
Any help here would be appreciated.

timneutkens commented Dec 17, 2020

Hi, thanks for creating an issue. We currently recommend using https://nextjs.org/docs/basic-features/built-in-css-support as zeit/next-css and zeit/next-sass have been deprecated in favor of the built-in support.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Оцените статью