Error postcss plugin tailwindcss requires postcss 8

Describe the problem: I've already installed a fresh project using vue 3 and typescript with vue cli 4, the app works fine but when i install the tailwind 2 and setup postcss.config.js i get th...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

boussadjra opened this issue

Nov 21, 2020

· 8 comments

Comments

@boussadjra

Describe the problem:

I’ve already installed a fresh project using vue 3 and typescript with vue cli 4, the app works fine but when i install the tailwind 2 and setup postcss.config.js i get the error cited above and the code will not be compiled, I tried to solve the problem by following the solutions in this issue but that doesn’t work for me

Link to a minimal reproduction:

my reproduction repository link

@DasdWaller

@boussadjra

Check this docs

I’ve already tried out that, it’s mentioned in the issue that I cited

@adamwathan

@adamwathan

Opened a pull request that adds the right dependencies:

boussadjra/vue3-tailwind2#1

To fix it I ran these commands from the instructions 👍🏻

npm uninstall tailwindcss postcss autoprefixer
npm install tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
sylann and HannesLinde reacted with thumbs up emoji
boussadjra, adityapandey9, patekfilip, pateskinasy, Asim-Tahir, mrzahidjabbar, tomdelie, DblK, RichardJong, adoxography, and 7 more reacted with heart emoji

@boussadjra

Thanks and sorry for commenting again, I pulled your changes in my local environment and I ran npm i after removing node_modules folder but when I run npm run serve it shows me again the same issue :

image

my env : windows 10, node 12.16.3, npm 6.14.5.

I tried out in codesandbox and it doesn’t work.

Edit compassionate-euclid-j6iwj

@adamwathan

Can you try deleting your package-lock.json/yarn.lock files in addition to node_modules and trying again? Would like to see the contents of package-lock.json after you do that.

Right now it’s still installing the wrong version of tailwindcss which is where that error is coming from.

CodeSandbox isn’t the best place to test this stuff because it doesn’t provide a proper build environment unless you use one of their server templates like Nuxt.js.

@boussadjra

Now after deleting package-lock.json and rerunning npm i it works , @adamwathan thank you very much for this awesome framework and your current help.

@warengonzaga

Hello Guys, How are you all? Hope You all Are Fine. Today As I Installed tailwindcss And just after installing I am Facing the following error Error: PostCSS plugin tailwindcss requires PostCSS 8 in nodeJs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

Contents

  1. How Error: PostCSS plugin tailwindcss requires PostCSS 8 Error Occurs ?
  2. How To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 ?
  3. Solution 1
  4. Solution 2
  5. Solution 3
  6. Solution 4
  7. Summery

Today As I Installed tailwindcss And just after installing I am Facing the following error.

Module build failed (from ./node_modules/postcss-loader/src/index.js):
Error: PostCSS plugin tailwindcss requires PostCSS 8.
Migration guide for end-users:
https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users

How To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 ?

  1. How To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 ?

    To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 Just uninstall Tailwind and re-install using the compatibility build instead. Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag.

  2. Error: PostCSS plugin tailwindcss requires PostCSS 8

    To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 Just uninstall Tailwind and re-install using the compatibility build instead. Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag.

Solution 1

Just uninstall Tailwind and re-install using the compatibility build instead:

npm uninstall tailwindcss postcss autoprefixer
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

The compatibility build is identical to the main build in every way, so you aren’t missing out on any features or anything like that.

Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag:

npm uninstall tailwindcss
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

Solution 2

This command worked for me.

npm install tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

Solution 3

Just run

npm uninstall tailwindcss postcss autoprefixer

then

vue add tailwind 

Solution 4

The solution below should work perfectly. Run the following commands

npm uninstall tailwindcss postcss autoprefixer

npm install tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also Read

  • SyntaxError: invalid syntax to repo init in the AOSP code.

Integration guides

Installing Tailwind CSS can be a slightly different process depending on what other frameworks/tools you’re using, so we’ve put together a bunch of guides that cover popular setups.

Don’t see your favorite tool in the list? We’re always working on new guides, but in the mean time you can follow the instructions for installing Tailwind CSS as a PostCSS plugin instead to get set up in no time.


Installing Tailwind CSS as a PostCSS plugin

Tailwind CSS requires Node.js 12.13.0 or higher.

For most real-world projects, we recommend installing Tailwind as a PostCSS plugin. Most modern frameworks use PostCSS under the hood already, and there’s a good chance you’ve used or are currently using other PostCSS plugins like autoprefixer.

If you’ve never heard of PostCSS or are wondering how it’s different from tools like Sass, read our guide on using PostCSS as your preprocessor for an introduction.

If this is a bit over your head and you’d like to try Tailwind without configuring PostCSS, read our instructions on using Tailwind CLI instead.

Install Tailwind via npm

For most projects (and to take advantage of Tailwind’s customization features), you’ll want to install Tailwind and its peer-dependencies via npm.

Since Tailwind does not automatically add vendor prefixes to the CSS it generates, we recommend installing autoprefixer to handle this for you like we’ve shown in the snippet above.

If you’re integrating Tailwind with a tool that relies on an older version of PostCSS, you may see an error like this:

In this case, you should install the PostCSS 7 compatibility build instead.

Add Tailwind as a PostCSS plugin

Add tailwindcss and autoprefixer to your PostCSS configuration. Most of the time this is a postcss.config.js file at the root of your project, but it could also be a .postcssrc file, or postcss key in your package.json file.

If you aren’t sure where PostCSS plugins are configured for the tools you’re using, you’ll want to refer to the documentation for those tools to learn where this should go. A search for “configure postcss {my tool}” will get you the answer pretty fast, too.

If you’re using any other PostCSS plugins, you should read our documentation on using PostCSS as your preprocessor for more details about the best way to order them with Tailwind.

Create your configuration file

If you’d like to customize your Tailwind installation, generate a config file for your project using the Tailwind CLI utility included when you install the tailwindcss npm package:

This will create a minimal tailwind.config.js file at the root of your project:

Learn more about configuring Tailwind in the configuration documentation.

Include Tailwind in your CSS

Create a CSS file if you don’t already have one, and use the @tailwind directive to inject Tailwind’s base, components, and utilities styles:

Tailwind will swap these directives out at build-time with all of the styles it generates based on your configured design system.

If you’re using postcss-import (or a tool that uses it under the hood, such as Webpacker for Rails), use our imports instead of the @tailwind directive to avoid issues when importing any of your own additional files:

If you’re working in a JavaScript framework like React or Vue that supports directly importing CSS files into your JS, you can also skip creating a CSS file altogether and import tailwindcss/tailwind.css instead which has all of these directives already in place:

Building your CSS

How you actually build your project will depend on the tools that you’re using. Your framework may include a command like npm run dev to start a development server that compiles your CSS in the background, you may be running webpack yourself, or maybe you’re using postcss-cli and running a command like postcss styles.css -o compiled.css.

If you’re already familiar with PostCSS you probably know what you need to do, if not refer to the documentation for the tool you are using.

When building for production, be sure to configure the purge option to remove any unused classes for the smallest file size:

Read our separate guide on optimizing for production to learn more about tree-shaking unused styles for best performance.

If you’re integrating Tailwind with a tool that relies on an older version of PostCSS, you may see an error like this when trying to build your CSS:

In this case, you should switch to our PostCSS 7 compatibility build instead.


Using Tailwind CLI

Tailwind CSS requires Node.js 12.13.0 or higher.

If you’d like to compile your CSS with Tailwind without integrating it directly into any sort of build tooling, you can use the Tailwind CLI tool to generate your CSS without configuring PostCSS or even installing Tailwind as a dependency if you don’t want to.

Use npx which is a tool that is automatically installed alongside npm to generate a fully compiled Tailwind CSS file:

This will create a file called tailwind.css generated based on Tailwind’s default configuration, and automatically add any necessary vendor prefixes using autoprefixer.

Now you can pull this file into your HTML just like any other stylesheet:

Watching for changes

You can use the --watch or -w flag to start a watch process and automatically rebuild your CSS any time you make any changes:

Using a custom CSS file

If you’d like to process any custom CSS alongside the default styles Tailwind generates, create a CSS file wherever you normally would and use the @tailwind directive to include Tailwind’s base, components, and utilities styles:

Then include the path to that file when building your CSS:

Read about adding base styles, extracting components, and adding new utilities to learn more about adding custom CSS on top of Tailwind.

Customizing your configuration

If you’d like to customize what Tailwind generates, create a tailwind.config.js file using the Tailwind CLI tool:

This will create a minimal tailwind.config.js file at the root of your project:

This file will automatically be read when building your CSS with Tailwind CLI:

If you’d like to keep your config file in a different location or give it a different name, pass the config file path using the -c option when building your CSS:

Learn more about configuring Tailwind in the configuration documentation.

Disabling Autoprefixer

By default, the Tailwind CLI tool will run your CSS through Autoprefixer to add any necessary vendor prefixes. If you already have Autoprefixer set up in your build pipeline somewhere further down the chain, you can disable it in the Tailwind CLI tool using the --no-autoprefixer flag to avoid running it twice:

Using a custom PostCSS configuration

If you’d like to use other PostCSS plugins alongside Tailwind, you can create a postcss.config.js file in your project root to add your extra plugins and Tailwind will include them if you use the --postcss flag when building your CSS:

By default, plugins are applied after Tailwind generates your CSS. If you have plugins that need to run before Tailwind, just include tailwindcss in your plugin list and Tailwind CLI will detect it and respect your custom plugin order:

If you’d like to automatically generate a basic postcss.config.js file when creating your tailwind.config.js file, use the --postcss or -p flag when initializing your config file:

Building for production

When building for production, set NODE_ENV=production on the command line when building your CSS:

This will make sure Tailwind removes any unused CSS for best performance. Read our separate guide on optimizing for production to learn more.

You can also use the --minify flag to compress your CSS with cssnano:


Using Tailwind via CDN

Before using the CDN build, please note that many of the features that make Tailwind CSS great are not available without incorporating Tailwind into your build process.

To get the most out of Tailwind, you really should install it as a PostCSS plugin.

To pull in Tailwind for quick demos or just giving the framework a spin, grab the latest default configuration build via CDN:

Note that while the CDN build is large (72.8kB compressed, 2936.0kB raw), it’s not representative of the sizes you see when including Tailwind as part of your build process.

Sites that follow our best practices are almost always under 10kb compressed.


HTML starter template

For Tailwind’s styles to work as expected, you’ll want to use the HTML5 doctype and include the responsive viewport meta tag to properly handle responsive styles on all devices.

Many front-end frameworks like Next.js, vue-cli and others do all this for you behind the scenes automatically, so depending on what you’re building you might not need to set this up.


PostCSS 7 compatibility build

As of v2.0, Tailwind CSS depends on PostCSS 8. Because PostCSS 8 is only a few months old, many other tools in the ecosystem haven’t updated yet, which means you might see an error like this in your terminal after installing Tailwind and trying to compile your CSS:

To help bridge the gap until everyone has updated, we also publish a PostCSS 7 compatibility build as @tailwindcss/postcss7-compat on npm.

If you run into the error mentioned above, uninstall Tailwind and re-install using the compatibility build instead:

The compatibility build is identical to the main build in every way, so you aren’t missing out on any features or anything like that.

Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag:

Содержание

  1. [Solved] Error: PostCSS plugin tailwindcss requires PostCSS 8
  2. How Error: PostCSS plugin tailwindcss requires PostCSS 8 Error Occurs ?
  3. How To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 ?
  4. Solution 1
  5. Solution 2
  6. Solution 3
  7. Solution 4
  8. Summery
  9. PostCSS plugin postcss-nested requires PostCSS 8 #2799
  10. Comments
  11. Describe the problem:
  12. PostCSS plugin tailwindcss requires PostCSS 8. #2854
  13. Either the corresponding version installed or the latest version will still report an error
  14. Replies: 8 suggested answers · 42 replies
  15. <>’s edit
  16. <>’s edit
  17. <>’s edit
  18. <>’s edit
  19. <>’s edit
  20. <>’s edit
  21. Установка
  22. Руководства по интеграции
  23. Установка Tailwind CSS в качестве плагина PostCSS
  24. Установить Tailwind через npm
  25. Добавить Tailwind как плагин PostCSS
  26. Создайте свой файл конфигурации
  27. Включите Tailwind в свой CSS
  28. Создание Вашего CSS
  29. Использование Tailwind CLI
  30. Следите за изменениями
  31. Использование собственного файла CSS
  32. Настройка Вашей конфигурации
  33. Отключение Autoprefixer
  34. Использование пользовательской конфигурации PostCSS
  35. Сборка для продакшена
  36. Использование Tailwind через CDN
  37. HTML стартовый шаблон
  38. Сборка совместимости с PostCSS 7

[Solved] Error: PostCSS plugin tailwindcss requires PostCSS 8

Hello Guys, How are you all? Hope You all Are Fine. Today As I Installed tailwindcss And just after installing I am Facing the following error Error: PostCSS plugin tailwindcss requires PostCSS 8 in nodeJs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Error: PostCSS plugin tailwindcss requires PostCSS 8 Error Occurs ?

Today As I Installed tailwindcss And just after installing I am Facing the following error.

How To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 ?

  1. How To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 ?

To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 Just uninstall Tailwind and re-install using the compatibility build instead. Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag.
Error: PostCSS plugin tailwindcss requires PostCSS 8

To Solve Error: PostCSS plugin tailwindcss requires PostCSS 8 Just uninstall Tailwind and re-install using the compatibility build instead. Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag.

Solution 1

Just uninstall Tailwind and re-install using the compatibility build instead:

The compatibility build is identical to the main build in every way, so you aren’t missing out on any features or anything like that.

Once the rest of your tools have added support for PostCSS 8, you can move off of the compatibility build by re-installing Tailwind and its peer-dependencies using the latest tag:

Solution 2

This command worked for me.

Solution 3

Solution 4

The solution below should work perfectly. Run the following commands

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Источник

PostCSS plugin postcss-nested requires PostCSS 8 #2799

Describe the problem:

When I upgraded Tailwind CSS to the version 2.0.1 inside my Next.js 10.0.2 (which should come with PostCSS 8, because Autoprefixer v10 works) project, it throw:

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

If using Next.js 10.0.2, ./node_modules/next/node_modules/postcss will be 8.1.7.
Probably, postcss-nested uses ./node_modules/postcss .

You can get around this by installing PostCSS 8 in your own project, but I don’t think it’s a fundamental solution.

@dqn it worked, but as you said, there should be a better solution

I just ran into the same problem.

I just ran into the same problem.

thanks it works

Note in case it helps anyone. if you get errors with the Postcss 7 npm installation above, try prefixing the ^ wildcard characters with a backslash — eg
npm install tailwindcss@compat postcss@^7 autoprefixer@^9

Using Next.js 10, I was able to install tailwindcss@compat and left the other plugins (like Autoprefixer) in their only-postcss8 version.

For compatibility with postcss v7, install these:

Also if you are using nextjs, install these too:

postcss-flexbugs-fixes released v5 recently supporting postcss 8. So we still need v4 for compatibilty.

In short:
yarn add tailwindcss@compat postcss@^7 autoprefixer@^7 postcss-flexbugs-fixes@^4 postcss-preset-env .

For Next.js 10 you don’t need the compatibility build, install Tailwind like this:

PostCSS and Autoprefixer need to be peer-dependencies as of PostCSS 8.

You can get around this by installing PostCSS 8 in your own project, but I don’t think it’s a fundamental solution.

It’s why we include postcss and autoprefixer in the installation instructions.

i got this too, I can come from @zeit/next-css let’s check for it. I removed it

I followed the steps in post-css-7-compatibility-build to upgrade tailwind to v2.x with vue 3 and it fails, it always raises that error.

@boussadjra Please open a new issue that includes a link to a GitHub repo that reproduces the problem.

Vue 3 works for me with the PostCSS 7 compatible install.

It doesn’t find plugins though

neither did other plugins like typography nor if I use npm:@tailwindcss

@StephanSchmidt please try to open a new issue where you put a link to reproduction repository

Hi,
Downgrade your autoprefixer to version 9, use

Do we still need to use postcss-flexbug-fixes along with tailwindcss? I’m using ejected create-react-app and want to add Tailwind in styleLoaders. My code is like below

even if I commented those other plugins, all just running well. But I’m afraid something will break.

@muhsalaa Not if you’re using tailwindcss version 2, IE support has been dropped. The bugs that was trying to fix don’t affect the latest browsers. You can checkout the affected browsers here: https://github.com/philipwalton/flexbugs

For compatibility with postcss v7, install these:

Also if you are using nextjs, install these too:

postcss-flexbugs-fixes released v5 recently supporting postcss 8. So we still need v4 for compatibilty.

In short:
yarn add tailwindcss@compat postcss@^7 autoprefixer@^7 postcss-flexbugs-fixes@^4 postcss-preset-env .

It is work for me.
My dependency list is as below.

Источник

PostCSS plugin tailwindcss requires PostCSS 8. #2854

Either the corresponding version installed or the latest version will still report an error

Beta Was this translation helpful? Give feedback.

16 You must be logged in to vote

I had the same thing with Vue 3 today. Solve it with the below.

<>’s edit

<>’s edit

when I did with yarn I received

Then some errors disapear.

You need to have

Beta Was this translation helpful? Give feedback.

4 You must be logged in to vote

thanks! solved for me adding postcss-loader

Beta Was this translation helpful? Give feedback.

<>’s edit

<>’s edit

I had the same thing with Vue 3 today. Solve it with the below.

Beta Was this translation helpful? Give feedback.

Marked as answer

29 You must be logged in to vote

Thanks. This worked for me !!

Beta Was this translation helpful? Give feedback.

This fixed my problem. Thank you so so much

Beta Was this translation helpful? Give feedback.

I had the same thing with Vue 3 today. Solve it with the below.

I don’t want to downgrade tailwindCSS to version 2.

Beta Was this translation helpful? Give feedback.

Beta Was this translation helpful? Give feedback.

Thanks! Now everything is working smoothly 👍🏾

Beta Was this translation helpful? Give feedback.

I got the flooring error when I ran

Beta Was this translation helpful? Give feedback.

5 You must be logged in to vote

npm install tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 —force

Beta Was this translation helpful? Give feedback.

Hmm. Any possible negative unintended consequences from adding «—force»?

Beta Was this translation helpful? Give feedback.

This post #3575 suggests the possible need to escape ^ by adding before each instance, so the revised code would be:

npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

Beta Was this translation helpful? Give feedback.

2 You must be logged in to vote

plus —force at the end, if you are so inclined

Beta Was this translation helpful? Give feedback.

<>’s edit

<>’s edit

Well, I decided to try the proposed solution and tried npm uninstall tailwindcss postcss autoprefixer per tailwind docs,

then npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 —force

which resulted in this error:

BTW, I’m using Vue 3.

From my package.json, after running the above:

Beta Was this translation helpful? Give feedback.

Источник

Установка

Узнайте, как запустить Tailwind CSS в своем проекте.

Руководства по интеграции

Процесс установки Tailwind CSS может немного отличаться в зависимости от того, какие другие фреймворки/инструменты вы используете, поэтому мы составили несколько руководств, которые охватывают популярные настройки.

Не видите свой любимый инструмент в списке? Мы постоянно работаем над новыми руководствами, но пока вы можете следовать инструкциям по установке Tailwind CSS в качестве плагина PostCSS вместо этого, чтобы получить настроен в кратчайшие сроки.

Установка Tailwind CSS в качестве плагина PostCSS

Tailwind CSS требует Node.js 12.13.0 или выше.

Для большинства реальных проектов мы рекомендуем установить Tailwind как плагин PostCSS. Большинство современных фреймворков уже используют PostCSS под капотом, и есть большая вероятность, что вы использовали или в настоящее время используете другие плагины PostCSS, такие как autoprefixer.

Если вы никогда не слышали о PostCSS или вам интересно, чем он отличается от таких инструментов, как Sass, прочтите наше руководство по использованию PostCSS в качестве препроцессора для введения.

Если это кажется вам непосильным и вы хотите попробовать Tailwind без настройки PostCSS, прочтите вместо этого наши инструкции по применению Tailwind CLI.

Установить Tailwind через npm

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

Поскольку Tailwind не добавляет автоматически префиксы поставщиков в создаваемый им CSS, мы рекомендуем установить autoprefixer для решения этой проблемы для Вас, как мы показали в приведенном выше фрагменте.

Если вы интегрируете Tailwind с инструментом, основанным на более старой версии PostCSS, вы можете увидеть такую ошибку:

Добавить Tailwind как плагин PostCSS

Добавьте tailwindcss и autoprefixer в Вашу конфигурацию PostCSS. В большинстве случаев это файл postcss.config.js в корне Вашего проекта, но это также может быть файл .postcssrc или ключ postcss в Вашем файле package.json .

Если вы не уверены, где настраиваются плагины PostCSS для используемых Вами инструментов, вам нужно обратиться к документации по этим инструментам, чтобы узнать, где это должно происходить. Поиск по запросу “configure postcss ” тоже даст вам ответ довольно быстро.

Если вы используете какие-либо другие плагины PostCSS, вам следует прочитать нашу документацию по использованию PostCSS в качестве препроцессора для получения более подробной информации о том, как лучше всего заказать их с помощью Tailwind.

Создайте свой файл конфигурации

Если вы хотите настроить установку Tailwind, сгенерируйте файл конфигурации для своего проекта с помощью утилиты Tailwind CLI, включенной при установке пакета npm tailwindcss :

Это создаст минимальный файл tailwind.config.js в корне Вашего проекта:

Узнайте больше о настройке Tailwind в документации по конфигурации.

Включите Tailwind в свой CSS

Создайте файл CSS, если у вас его еще нет, и используйте директиву @tailwind для внедрения стилей Tailwind base , components и utilities :

Tailwind заменит эти директивы во время сборки на все стили, которые он генерирует на основе Вашей настроенной дизайн-системы.

Если вы используете postcss-import (или инструмент, который использует его под капотом, например Webpacker для Rails), используйте наш импорт вместо директивы @tailwind , чтобы избежать проблем при импорте любых Ваших собственных дополнительных файлов:

Если вы работаете в среде JavaScript, такой как React или Vue, которая поддерживает прямой импорт файлов CSS в ваш JS, вы также можете полностью отказаться от создания файла CSS и вместо этого импортировать tailwindcss/tailwind.css , в котором все эти директивы уже есть в место:

Создание Вашего CSS

То, как вы на самом деле создаете свой проект, будет зависеть от инструментов, которые вы используете. Ваша структура может включать команду типа npm run dev для запуска сервера разработки, который компилирует ваш CSS в фоновом режиме, вы можете запускать webpack самостоятельно, или, может быть, вы используете postcss-cli и запускаете такую команду, как postcss styles.css -o compiled.css .

Если вы уже знакомы с PostCSS, Вы, вероятно, знаете, что вам нужно делать, если не обратитесь к документации для инструмента, который вы используете.

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

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

Если вы интегрируете Tailwind с инструментом, основанным на более старой версии PostCSS, вы можете увидеть такую ошибку при попытке создать свой CSS:

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

Tailwind CSS требует Node.js 12.13.0 или выше.

Если вы хотите скомпилировать свой CSS с помощью Tailwind, не интегрируя его напрямую в какие-либо инструменты сборки, вы можете использовать инструмент Tailwind CLI для создания своего CSS без настройки PostCSS или даже установки Tailwind в качестве зависимости, если вы не хотите .

Используйте npx , инструмент, который автоматически устанавливается вместе с npm , чтобы сгенерировать полностью скомпилированный файл CSS Tailwind:

Это создаст файл с именем tailwind.css , сгенерированный на основе конфигурации Tailwind по умолчанию, и автоматически добавит любого необходимого поставщика префиксов с использованием autoprefixer.

Теперь вы можете вставить этот файл в свой HTML, как и любую другую таблицу стилей:

Следите за изменениями

Вы можете использовать флаг —watch или -w , чтобы запустить процесс просмотра и автоматически перестраивать свой CSS каждый раз, когда вы вносите какие-либо изменения:

Использование собственного файла CSS

Если вы хотите обрабатывать любой пользовательский CSS вместе со стилями по умолчанию, которые генерирует Tailwind, создайте файл CSS в любом месте и используйте директиву @tailwind для включения стилей Tailwind base , components и utilities :

Затем укажите путь к этому файлу при создании CSS:

Прочтите о добавлении базовых стилей, извлечении компонентов, и добавлении новых утилит, чтобы узнать больше о добавлении пользовательского CSS поверх Tailwind.

Настройка Вашей конфигурации

Если вы хотите настроить то, что генерирует Tailwind, создайте файл tailwind.config.js с помощью инструмента Tailwind CLI:

Это создаст минимальный файл tailwind.config.js в корне Вашего проекта:

Этот файл будет автоматически прочитан при создании вашего CSS с помощью Tailwind CLI:

Если вы хотите сохранить файл конфигурации в другом месте или дать ему другое имя, передайте путь к файлу конфигурации, используя параметр -c при создании CSS:

Узнайте больше о настройке Tailwind в документации по конфигурации.

Отключение Autoprefixer

По умолчанию инструмент Tailwind CLI будет запускать ваш CSS через Autoprefixer для добавления любых необходимых префиксов поставщиков. Если у вас уже есть Autoprefixer, настроенный в конвейере сборки где-то дальше по цепочке, вы можете отключить его в инструменте Tailwind CLI с помощью флага —no-autoprefixer , чтобы не запускать его дважды:

Использование пользовательской конфигурации PostCSS

Если вы хотите использовать другие плагины PostCSS вместе с Tailwind, вы можете создать файл postcss.config.js в корне вашего проекта, чтобы добавить дополнительные плагины, и Tailwind будет включать их, если вы используете флаг —postcss , когда создание вашего CSS:

По умолчанию плагины применяются после того, как Tailwind сгенерирует ваш CSS. Если у вас есть плагины, которые необходимо запустить до Tailwind, просто включите tailwindcss в свой список плагинов, и интерфейс командной строки Tailwind обнаружит его и соблюдает ваш собственный порядок плагинов:

Если вы хотите автоматически сгенерировать базовый файл postcss.config.js при создании файла tailwind.config.js , используйте флаг —postcss или -p при инициализации файла конфигурации:

Сборка для продакшена

При сборке для продакшена установите NODE_ENV=production в командной строке при сборке CSS:

Это гарантирует, что Tailwind удалит все неиспользуемые CSS для лучшей производительности. Прочтите наше отдельное руководство по оптимизации для продакшена, чтобы узнать больше.

Вы также можете использовать флаг —minify для сжатия вашего CSS с помощью cssnano:

Использование Tailwind через CDN

Перед использованием сборки CDN обратите внимание, что многие функции, которые делают Tailwind CSS отличным, недоступны без включения Tailwind в процесс сборки.

вы не можете настроить тему по умолчанию Tailwind

вы не можете использовать такие директивы, как @apply , @variants и т.д.

вы не можете включить дополнительные варианты, например group-focus

вы не можете устанавливать сторонние плагины

вы не можете избавиться от неиспользуемых стилей

Чтобы получить максимальную отдачу от Tailwind, вам действительно следует установить его как плагин PostCSS.

Чтобы использовать Tailwind для быстрых демонстраций или просто попробовать фреймворк, загрузите последнюю сборку конфигурации по умолчанию через CDN:

NotОбратите внимание, что, хотя сборка CDN велика ( 72.8kB в сжатом виде, 2936.0kB в исходном), она не соответствует размерам, которые вы видите при включении Tailwind как части процесса сборки..

Сайты, которые следуют нашим лучшим практикам, почти всегда имеют после сжатия менее 10КБ.

HTML стартовый шаблон

Чтобы стили Tailwind работали должным образом, вы захотите использовать тип документа HTML5 и включить метатег адаптивного окна просмотра для правильной обработки адаптивных стилей на всех устройствах.

Многие интерфейсные фреймворки, такие как Next.js, vue-cli и другие, делают все это за вас за кулисами автоматически, поэтому в зависимости от того, что вы создаете, Вам, возможно, не нужно это настраивать.

Сборка совместимости с PostCSS 7

Начиная с версии 2.0, Tailwind CSS зависит от PostCSS 8. Поскольку PostCSS 8 всего несколько месяцев, многие другие инструменты в экосистеме еще не обновлены, что означает, что вы можете увидеть такую ошибку в своем терминале после установки Tailwind и пытаемся скомпилировать ваш CSS:

Чтобы сократить разрыв до тех пор, пока все не обновятся, мы также публикуем сборку совместимости с PostCSS 7 как @tailwindcss/postcss7-compat на npm.

Если вы столкнулись с упомянутой выше ошибкой, удалите Tailwind и переустановите его, используя вместо этого сборку совместимости:

Сборка совместимости идентична основной сборке во всех отношениях, поэтому вы не упускаете ни одной функции или чего-либо в этом роде.

После того, как остальные Ваши инструменты добавят поддержку PostCSS 8, вы можете отказаться от сборки совместимости, переустановив Tailwind и его одноранговые зависимости, используя тег latest :

Источник

I installed the new tailwindcss version 2.0 and I’ve got the following error. I tried to uninstall postcss and tailwindcss but it does not work. Need help.


Module build failed (from ./node_modules/postcss-loader/src/index.js):
Error: PostCSS plugin tailwindcss requires PostCSS 8.
Migration guide for end-users:
https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
    at Processor.normalize (/Users/niklas/Desktop/Privat/Projekte/nifoschool-frontend/node_modules/postcss-loader/node_modules/postcss/lib/processor.js:153:15)
    at new Processor (/Users/niklas/Desktop/Privat/Projekte/nifoschool-frontend/node_modules/postcss-loader/node_modules/postcss/lib/processor.js:56:25)
    at postcss (/Users/niklas/Desktop/Privat/Projekte/nifoschool-frontend/node_modules/postcss-loader/node_modules/postcss/lib/postcss.js:55:10)
    at /Users/niklas/Desktop/Privat/Projekte/nifoschool-frontend/node_modules/postcss-loader/src/index.js:140:12

 @ ./node_modules/vue-style-loader??ref--6-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-oneOf-1-2!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/util/SlideInfo.vue?vue&type=style&index=0&lang=css& 4:14-393 14:3-18:5 15:22-401
 @ ./src/components/util/SlideInfo.vue?vue&type=style&index=0&lang=css&
 @ ./src/components/util/SlideInfo.vue
 @ ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/Grades.vue?vue&type=script&lang=js&
 @ ./src/views/Grades.vue?vue&type=script&lang=js&
 @ ./src/views/Grades.vue
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://172.20.12.3:8081&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

Here is my package.json

  "name": "nifo-school",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "electron:build": "vue-cli-service electron:build",
    "electron:serve": "vue-cli-service electron:serve",
    "postinstall": "electron-builder install-app-deps",
    "postuninstall": "electron-builder install-app-deps"
  },
  "main": "background.js",
  "dependencies": {
    "react": "^16.3.0",
    "@ivanv/vue-collapse-transition": "^0.2.1",
    "autoprefixer": "^10.0.2",
    "axios": "^0.21.0",
    "core-js": "^3.6.5",
    "electron": "^8.0.0",
    "electron-drag": "^2.0.0",
    "jquery": "^3.5.1",
    "js-cookie": "^2.2.1",
    "postcss-cli": "^=8.0",
    "react-collapse": "^5.0.1",
    "summernote": "^0.8.18",
    "tailwindcss": "^2.0.1",
    "v-click-outside": "^3.1.2",
    "vue": "^2.6.11",
    "vue-html-editor": "^0.2.1",
    "vue-i18n": "^8.22.1",
    "vue-router": "^3.2.0",
    "vue2-editor": "^2.10.2",
    "vuex": "^3.5.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-airbnb": "^5.0.2",
    "babel-eslint": "^10.1.0",
    "electron-devtools-installer": "^3.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-vue": "^6.2.2",
    "lint-staged": "^9.5.0",
    "node-sass": "^4.12.0",
    "postcss": "^=8.1",
    "sass-loader": "^8.0.2",
    "vue-cli-plugin-electron-builder": "~2.0.0-rc.4",
    "vue-template-compiler": "^2.6.11"
  },
  "gitHooks": {
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.{js,jsx,vue}": [
      "vue-cli-service lint",
      "git add"
    ]
  }
}```


Thanks for help
1) Solution

You’re integrating Tailwind with a tool that relies on an older version of PostCSS. You can use this doc https://tailwindcss.com/docs/installation#post-css-7-compatibility-build

2) Solution
npm uninstall tailwindcss postcss autoprefixer

then

vue add tailwind 

to use the vue cli plugin https://www.npmjs.com/package/vue-cli-plugin-tailwind

3) Solution

worked for me :

npm install [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9
4) Solution

This solution below should work perfectly.

Run the following commands. Remove the -D from the npm uninstall command if you originally installed tailwind etc as regular dependencies rather than dev dependencies.

npm uninstall -D tailwindcss postcss autoprefixer

npm install -D [email protected]:@tailwindcss/postcss7-compat  [email protected]^7 [email protected]^9
5) Solution

Uninstall Tailwind and re-install using the compatibility build instead

npm uninstall tailwindcss postcss autoprefixer
npm install [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9
6) Solution

I was getting dependency tree error when I try uninstall and install with compact version. So I had to install with yarn instead and it works.

npm uninstall tailwindcss postcss autoprefixer
yarn add [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9
7) Solution

The accepted answer is now out of date.

As of v2.0, Tailwind CSS depends on PostCSS 8. The previously accepted answer states how to downgrade to PostCSS 8

Instead please do the following to get everything running on all the latest versions

yarn add @storybook/addon-postcss

Then edit your .storybook/main.js

module.exports = {
  stories: [
    "../stories/**/*.stories.mdx",
    "../stories/**/*[email protected](js|jsx|ts|tsx)",
  ],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    {
      name: "@storybook/addon-postcss",
      options: {
        postcssLoaderOptions: {
          implementation: require("postcss"),
        },
      },
    },
  ],
};

https://storybook.js.org/addons/@storybook/addon-postcss

@dlporter98

8) Solution

you have to uninstall all these

npm uninstall autoprefixer postcss tailwindcss

Then run this command, it’s will generate tailwind.css file automatically

vue add tailwind 
9) Solution

To resolve this error, uninstall Tailwind and re-install using the compatibility build instead:

npm uninstall tailwindcss postcss autoprefixer

npm install -D [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9

Solution from Tailwind documentation v2

10) Solution

With Vue 3 and Tailwindcss 3

  1. Create tailwind.config.js
  2. Create postcss.config.js
  3. Add following in postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {
      config: './tailwind.config.js'
    }
  }
}

The above configuration works fine with latest postcss, autoprefixer, vue 3 and tailwind 3

11) Solution

The above solution fixed TaildWindCss PostCss issue, but I faced another error, which is :

TypeError: getProcessedPlugins is not a function

The Solution for is to upgrade Node version, in my case I upgraded from v10 to v15 which fixed my issue.

12) Solution

Oddly I had this issue on one dev machine . . . but not the other, with identical package.json file, and using identical node/npm (15.5/7.3). I deleted node_modules, reinstalled. Did not fix it.

Final fix, which is bizarre, is after the node module reinstall, all I did was:

npm uninstall tailwindcss

then

npm i tailwindcss --save-dev

(note, not using the compatibility package) and it worked fine. I do have to use --legacy-peer-deps when re-installing the node_modules, so somehow the order of installation mattered in my scenario . . .

13) Solution

I got the same issue using laravel 8, So Try uninstalling tailwind using «npm uninstall tailwindcss» and install it back using

npm install [email protected]

then run «npx tailwindcss init» if you don’t have the tailwing.config.js file

after then run npm run watch.

still follow up the laravel documentation for more when you get stuck
https://laravel.com/docs/8.x/mix#tailwindcss

14) Solution

For those upgrading to Tailwind 3, and experiencing this issue, the following instructions from Tailwind’s own troubleshooting are what fixed it for me.

Specifically, changing your start and build scripts:

"start": "concurrently "npm run start:css" "react-scripts start"",
"start:css": "tailwindcss -o src/tailwind.css --watch",
"build": "tsc && npm run build:css && react-scripts build",
"build:css": "NODE_ENV=production tailwindcss -o src/tailwind.css -m",

You’ll have to install concurrently and npm-run-all, though.

The following is my postcss.config.js:

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

This will mean that you’ll have to import tailwind.css instead of index.css in your index file index.{tsx,js} for the project.

And if this worked for you, keep in mind you might no longer need @craco/craco installed.

15) Solution

I’m on a Mac using VueJS 3 (@vue/cli 4.5.11). For me the following two commands solved the issue:

npm uninstall tailwindcss postcss autoprefixer
npm install -D [email protected] [email protected] [email protected]

This installed:

  • tailwindcss 2.1.1
  • postcss 8.2.10
  • autoprefixer 10.2.5
16) Solution

I tried everything and was still having TypeError: getProcessedPlugins is not a function error. What fixed the issue for me was upgrading the nodejs version.

To check the installed node version

node -v

my node version was v10.23.0 and was using Ubuntu. I upgraded to v14.15.4.

Here is how I upgraded node

sudo apt update
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
sudo apt-get install -y nodejs
node -v

also I cleaned the cache to be more sure

npm cache clean -f

After upgrading I deleted node_modules folder inside project. ran npm install and then ran npm run dev inside the project folder.

This is the only solution that worked for me, so sharing it.

17) Solution

I also faced this issue while upgrading. previously I done the setup using postCSS.

official documentation says

Note that Tailwind CSS v3.0 requires PostCSS 8, and no longer supports PostCSS 7. If you can’t upgrade to PostCSS 8, we recommend using Tailwind CLI instead of installing Tailwind as a PostCSS plugin.

So this time i done the setup using cli. https://tailwindcss.com/docs/installation

  1. yarn remove tailwindcss postcss autoprefixer
    yarn add --dev [email protected] @tailwindcss/[email protected] @tailwindcss/[email protected] @tailwindcss/[email protected] @tailwindcss/[email protected] [email protected] [email protected]

  2. npx tailwindcss -i ./src/assets/css/style.css -o ./src/assets/css/tailwind.css --watch

And in package.json need to do this change

https://tailwindcss.com/docs/content-configuration#it-just-isn-t-working-properly

my package.json

"start": "concurrently "npm run start:css" "react-scripts start"",
"start:css": "tailwindcss -o src/assets/css/tailwind.css --watch",
"build": "tsc && npm run build:css && react-scripts build",
"build:css": "NODE_ENV=production tailwindcss -o src/assets/css/tailwind.css -m",

This answer helped me to resolve the issue https://stackoverflow.com/a/70492649/7225816

18) Solution

This worked for me:
running «npm install tailwindcss postcss»
and «npm install tailwindcss autoprefixer»

this seperates installation of postcss and autoprefixer independently.

19) Solution

npm install [email protected] [email protected] [email protected]

20) Solution

You gotta uninstall the tailwindcss, postcss, and autoprefixer and then install the compatible versions:

npm uninstall tailwindcss postcss autoprefixer
npm install [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9
21) Solution

Had the same issue and did the following to resolve;

  1. Check your npm version using npm -ver, and make sure to install the latest version
  2. Also check your Node version and update to the latest version through this URL: «https://nodejs.org/en/download/»
22) Solution

While not using Vue, I hope this helps others with a similar issue. In my case, I was using TailwindCSS with Gulp (^4.0.2) and was able to solve the error by removing tailwind and its dependencies:

npm uninstall tailwindcss gulp-postcss autoprefixer

Then installed them again but explicitly specified the postcss plugin as version 9:

npm install tailwindcss autoprefixer [email protected]

I tried with [email protected], but found it kept installing version 8.3.1 and didn’t resolve the error. More information can be seen here: https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users

Otherwise, I would echo the use of the Tailwind compatibility version.

23) Solution

Yarn equivalent for those who are stuck with PostCSS v8 due to using a framework like Vuepress v1:

yarn add -D [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9

24) Solution

Just uninstall Tailwind and re-install using the compatibility build instead:

npm uninstall tailwindcss postcss autoprefixer
npm install -D [email protected]:@tailwindcss/postcss7-compat [email protected]^7 [email protected]^9
25) Solution

npm uninstall tailwindcss
npm install -D [email protected] [email protected] [email protected]

Comments Section

Vue 3 is one thing that does not yet have postcss 8 support. The guide above works great without hassle.

they need to fix this thing soon. I ecnounter the same when I was trying to use it last week with vue cli project and today with parcelJS project. Thank you

I get the following errors: npm ERR! ERESOLVE unable to resolve dependency tree,npm ERR! Found: [email protected] Any help?

I get the following errors: npm ERR! ERESOLVE unable to resolve dependency tree,npm ERR! Found: [email protected] Any help?

thanks ,,, this is a live saver ,, fixed my issue with laravel breeze installation

The second line errors out with Error code E404… I’ll edit your post to properly reflect what it should be, In future though, Be more explanative in your answers

This did not work for me on laravel 8, however this did: tailwindcss.com/docs/…

I’m using Vue 3.0.7, which should have support for PostCSS 8, but I still get this error. My package-lock.json shows that the PostCSS is at v8.2.7, and I can’t install the compat build because it conflicts with the PostCSS 8 requirement in @vue/compiler-sfc 3.0.7.

I’m using Vue2, and this workaround doesn’t work.

If you run into issues, you may need to use our PostCSS 7 compatibility build instead. tailwindcss.com/docs/…

Confirmed working with latest Vue3 + Typescript.

It’s a good idea to install these with --save-dev or -D since they’re only dev dependencies.

In my case I was using Yarn 2+, which also doesn’t work. Downgrading Yarn for this project to 1 solved the problem.

You need storybook for tailwind?

A thread on Tailwind’s GitHub (sorry, no link) suggests each ^ may need to be escaped with an before each instance of ^

A thread on Tailwind’s GitHub (sorry, no link) suggests each ^ may need to be escaped with an before each instance of ^

For yarn 2, yarn add [email protected]:@tailwindcss/[email protected]^2.0.2 [email protected]^7 [email protected]^9

This solution indeed worked for my environment.

Great for those using vue cli. I used vite procedure that was why I got that error.

This doesn’t work for me. I’m getting Cannot find module postcss-import

Does this fix the issue and allow for Tailwind 3?

It is getting ridiculous. 2022, and it is still kind of broken?

Yes this worked for me. thanks. also need to follow this steps if setup was done using postCSS previously. Right now need to use tailwindCLI to do the setup. Note that Tailwind CSS v3.0 requires PostCSS 8, and no longer supports PostCSS 7. If you can’t upgrade to PostCSS 8, we recommend using Tailwind CLI instead of installing Tailwind as a PostCSS plugin. tailwindcss.com/docs/upgrade-guide tailwindcss.com/docs/installation

Second line — npm ERR! Cannot read property ‘name’ of null

There is no need to downgrade to PostCSS 7, you can now easily get this working with PostCSS 8 — see stackoverflow.com/a/68605148/840897

Legend. I ran npm uninstall tailwindcss postcss autoprefixer first but this sorted it for me. Build was successful. Thanks a bunch!

Works well with Vue3 + TS

Not everyone is running storybook who’s seeing this error (i’m one of them)….

The second line has an extra @tailwindcss/postcss7-compat that causes the problem. I’ll edit the answer to remove it.

Related Topics
javascript
node.js
npm
tailwind-css

Mentions
Dharman
Ram
Aaron
Sebastian
Dylan Pierce
Saurabh
Eugene
Anonymous User
Aimme
Edie Lemoine
Bilal
Hasip Timurtas
Nifo
Khalid Edaig
Jovialcore
Theakash
Jimba Tamang
Mhammed Talhaouy
Adetoro
Reda Makhchan
Michael Oliver
Arinzehills
Evgeny Astapov
David Md
M Yadav
Alshafi
Supapon Pick Pucknavin
Noor Khan
Niklas Forst
Metadaddy

References
stackoverflow.com/questions/64925926/error-postcss-plugin-tailwindcss-requires-postcss-8

Tailwindcss is a utility-first CSS framework loaded with classes that help you design almost any design without leaving the HTML. In this article, we are going to learn how to integrate the tailwindcss with React.

Getting Started

Let’s create your react project. We are going to use the create-react-app to setup everything related to React quickly.

npx create-react-app reactailwind

Now go to your project directory cd reactailwind and install the tailwindcss.

Install Tailwind

Tailwind requires to install its peer-dependencies such as postcss and autoprefixer. If you don’t have installed the postcss and autoprefixer to your project then create with the following command.

npm -i -D tailwindcss postcss autoprefixer

Why autoprefixer with Tailwind?

Tailwind does not automatically add vendor prefixes to the CSS it generates, we recommend installing autoprefixer to handle this for you

https://tailwindcss.com/docs/installation

Error: PostCSS plugin tailwindcss requires PostCSS 8

I face this issue while integrating Tailwind with CRA. To resolve this issue I simply installed the PostCSS module.

npm -i postcss

Generate Tailwind Configuration

We can generate the Tailwind configuration file by the following command.

npx tailwindcss init

The above command will generate a blank configuration file, that you can customize according to project need. Let’s keep this file as it is.

module.exports = {
    purge: [],
    darkMode: false, // or 'media' or 'class'
    theme: {
        extend: {},
    },
    variants: {
        extend: {},
    },
    plugins: [],
}

Set-up PostCSS Configuration

Let’s create a postcss.config.js file to configure it for tailwind.

touch postcss.config.js

Open the postcss.config.js file and paste the following codes to it.

const tailwindcss = require("tailwindcss");
module.exports = {
    plugins: [
        tailwindcss("./tailwind.config.js"),
        require("autoprefixer")
    ]
};

Create Global CSS

Next, create a CSS file and import the base, components and utilities from tailwind. I have created a file global.css under /src/styles/global.css

@tailwind base;
@tailwind components;
@tailwind utilities;

Connect Tailwind, PostCSS and React

Now, open the package.json and change the scripts. This is how it looks before editing.

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

Modify it with the following

"scripts": {
    "start": "npm run watch:css && react-scripts start",
    "build": "npm run build:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:css": "postcss src/styles/global.css -o src/styles/main.css",
    "watch:css": "postcss src/styles/global.css -o src/styles/main.css"
},

As you noticed, we have created two new commands watch:css and build:css that runs the postcss command. We added the source for the global style and the output path to the postcss command.

Now open the App.js file and add the compiled style by postcss.

import './styles/main.css';

We hope this article will help you to learn the setting up tailwindcss with react. If you like this article then please follow us on Facebook and Twitter.

Понравилась статья? Поделить с друзьями:
  • Error pos vert variance
  • Error portal mod скачать
  • Error popup closed by user
  • Error popup android
  • Error populating transaction anaconda is retrying при установке centos