简体   繁体   English

Tailwindcss 不适用于 next.js; 配置有什么问题?

[英]Tailwindcss not working with next.js; what is wrong with the configuration?

For some reason, tailwind is not rendering properly in next.js.出于某种原因, tailwind在 next.js 中没有正确呈现。

I'm wondering if something is wrong with my settings?我想知道是不是我的设置有问题?

Styles folder - tailwind.css Styles 文件夹 - tailwind.css

@tailwind base; @顺风基地;

/* Write your own custom base styles here */

/* Start purging... */
@tailwind components;
/* Stop purging. */

/* Write you own custom component styles here */
.btn-blue {
  @apply bg-blue-500 text-white font-bold py-2 px-4 rounded;
}

/* Start purging... */
@tailwind utilities;
/* Stop purging. */

/* Your own custom utilities */

.... ....

_app.js _app.js

import React from "react";
// import "styles/global.scss";


import 'styles/tailwind.css'


import NavbarCustom from "components/Layout/NavbarCustom";
import Footer from "components/Layout/Footer";
import "util/analytics.js";
import { ProvideAuth } from "util/auth.js";

function MyApp({ Component, pageProps }) {
  return (
    <ProvideAuth>
      <>
        <NavbarCustom
          bg="white"
          variant="light"
          expand="md"
          logo="icons/Logo_512px.png"
        />

        <Component {...pageProps} />

What am I doing wrong?我究竟做错了什么? so confused, usually this sort of setup is fine.如此困惑,通常这种设置很好。

This is the site btw - https://moodmap.app/ .这是网站 btw - https://moodmap.app/

using the information below, made changes and still same issue weirdly.使用下面的信息,进行了更改,但奇怪的是仍然是同样的问题。

https://moodmap.app/ is the site example. https://moodmap.app/是站点示例。

tailwind.config.js tailwind.config.js

module.exports = {
  future: {
    removeDeprecatedGapUtilities: true,
  },
  purge: ['./components/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      colors: {
        'accent-1': '#333',
      },
    },
  },
  variants: {},
  plugins: [],
}

postcss.config.js postcss.config.js

module.exports = {
    plugins: [
      'tailwindcss',
      'postcss-flexbugs-fixes',
      [
        'postcss-preset-env',
        {
          autoprefixer: {
            flexbox: 'no-2009',
          },
          stage: 3,
          features: {
            'custom-properties': false,
          },
        },
      ],
    ],
  }

{
  "name": "MoodMap",
  "version": "0.1.0",
  "private": true,
  "keywords": [
    "MoodMap"
  ],
  "dependencies": {
    "@analytics/google-analytics": "0.2.2",
    "@stripe/stripe-js": "^1.5.0",
    "analytics": "0.3.1",
    "fake-auth": "0.1.7",
    "mailchimp-api-v3": "1.13.1",
    "next": "9.5.3",
    "query-string": "6.9.0",
    "raw-body": "^2.4.1",
    "rc-year-calendar": "^1.0.2",
    "react": "16.12.0",
    "react-dom": "16.12.0",
    "react-hook-form": "4.10.1",
    "react-query": "2.12.1",
    "react-transition-group": "^4.4.1",
    "stripe": "^8.52.0"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "stripe-webhook": "stripe listen --forward-to localhost:3000/api/stripe-webhook"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "postcss-flexbugs-fixes": "^4.2.1",
    "postcss-preset-env": "^6.7.0",
    "stylelint": "^13.7.1",
    "stylelint-config-standard": "^20.0.0",
    "tailwindcss": "^1.8.9"
  }
}

Thanks!谢谢!

The same issue with my project, but I try to change the globals.css like this:我的项目也有同样的问题,但我尝试像这样更改globals.css

before

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900');

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

after

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import './base.css';
@import 'tailwindcss/utilities';

For devs that created their project with nextJS.对于使用 nextJS 创建项目的开发人员。

be aware that the content of the tailwind.config.js needs the correct paths to the files.请注意, tailwind.config.js的内容需要正确的文件路径。

module.exports = {
  content: ["./pages/*.{html,js,jsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

For example, if you create a project with nextjs for example, you have a pages folder, where your index.js file is located.例如,如果您使用 nextjs 创建一个项目,那么您有一个pages文件夹,您的index.js文件就位于该文件夹中。 Therefore the code snippet (see below) on https://tailwindcss.com/docs/installation/using-postcss is not perfectly matching.因此https://tailwindcss.com/docs/installation/using-postcss上的代码片段(见下文)并不完全匹配。 Change it to the above or your own liking.将其更改为上述或您自己的喜好。

module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

For me the solution was adding ./src/... to content sources in tailwind.config.js .对我来说,解决方案是将./src/...添加到tailwind.config.js的内容源中。 Official Next.JS + Tailwindcss example doesn't support src folder.官方 Next.JS + Tailwindcss 示例不支持 src 文件夹。

One of my projects had those package versions installed我的一个项目安装了这些软件包版本

"next": "11.1.0",
"autoprefixer": "^10.3.3",
"postcss": "^8.3.6",
"tailwindcss": "^2.2.8"

this setting in tailwind.config.js was working: tailwind.config.js中的此设置有效:

module.exports = {
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
};

Recently I started a new project with these packages:最近我用这些包开始了一个新项目:

"next": "12.0.8",
"autoprefixer": "^10.4.2",
"postcss": "^8.4.5",
"tailwindcss": "^3.0.15"

The previous config setting was not working.以前的配置设置不起作用。 So I changed it to :所以我将其更改为:

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

I followed the official tutorial to install TailwindCSS into my NextJS app from here — https://tailwindcss.com/docs/guides/nextjs - but still couldn't get things working.我按照官方教程从这里将 TailwindCSS 安装到我的 NextJS 应用程序 — https://tailwindcss.com/docs/guides/nextjs — 但仍然无法正常工作。

It turns out that I had forgotten to import global.css into my main app file.事实证明,我忘记将global.css导入到我的主应用程序文件中。

Adding -添加 -

import "../styles/globals.css";

into _app.tsx solved it for me.进入 _app.tsx 为我解决了它。

I got mine to work in the weirdest way after hours of fiddling with it;经过几个小时的摆弄,我让我的工作以最奇怪的方式工作; I just added a class to an element in one of my components and then wrote custom CSS for that class in the global.css file, then all tailwinds classes reflected.我只是在我的一个组件中的一个元素中添加了一个类,然后在 global.css 文件中为该类编写了自定义 CSS,然后反映了所有尾风类。 This might be a bug in tailwind's code that they need to trace and fix.这可能是他们需要跟踪和修复的 tailwind 代码中的错误。

For people who are still having an issue with following versions:对于以下版本仍有问题的人:

"autoprefixer": "^10.4.7",
"postcss": "^8.4.13",
"tailwindcss": "^3.0.24",

in a Nx + Next.js environment, you can simply use following config files:在 Nx + Next.js 环境中,您可以简单地使用以下配置文件:

// postcss.config.js
const { join } = require('path');

module.exports = {
  plugins: {
    tailwindcss: {
      config: join(__dirname, 'tailwind.config.js'),
    },
    autoprefixer: {},
  },
};

// tailwind.config.js
const { join } = require('path');

module.exports = {
  content: [
    join(__dirname, './pages/**/*.{js,ts,jsx,tsx}'),
    join(__dirname, './src/**/*.{js,ts,jsx,tsx}'),
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

In my case, I had set up the Tailwind config file correctly, but tailwind styles were not applying.就我而言,我已经正确设置了 Tailwind 配置文件,但没有应用 Tailwind 样式。 Deleting the .next folder and running next dev helped.删除.next文件夹并运行next dev有所帮助。

I had the same issue in some files.我在某些文件中遇到了同样的问题。

After removing all inline tailwind classes and putting them in CSS files with @apply it works well.在删除所有内联顺风类并使用@apply将它们放入 CSS 文件后,它运行良好。

I think your setup is too big.我觉得你的设置太大了。 You can achieve this with much simpler stuff nowdays.现在你可以用更简单的东西来实现这一点。

First, I don't think CSS needs to be loaded into nextjs anymore and modules are supported natively.首先,我认为不再需要将 CSS 加载到 nextjs 中,并且原生支持模块。 (So you can delete this withCSS stuff) (所以你可以用CSS的东西删除这个)

Second, tailwind doesn't need such elaborate setup anymore, if you are using the newer versions.其次,如果您使用较新的版本,顺风不再需要如此复杂的设置。

So you will need to install postcss-preset-env, but it does remove the need for big config now.所以你需要安装 postcss-preset-env,但它现在确实不需要大配置。

Check out this example https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss查看此示例https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss

I have experienced this too, but my solution was to edit the tailwind.connfig.js我也遇到过这种情况,但我的解决方案是编辑 tailwind.connfig.js

Depending with the version取决于版本

For version 2对于版本 2

module.exports = {
 purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
 theme: {
   extend: {},
 },
 variants: {
   extend: {},
 },
 plugins: [],
}

For version 3对于版本 3

module.exports = {
  content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

 module.exports = { content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}', './containers/**/*.{js,ts,jsx,tsx}'], theme: { extend: {}, }, variants: { extend: {}, }, plugins: [], } <!-- You have to add paths to folders in which you are using tailwindcss in the tailwind.config.js file --> <!-- Example: I add './containers/**/*.{js,ts,jsx,tsx}' to the "content"-->

另一个简单的潜在原因是组件/页面文件夹拼写错误 - 确保它们拼写正确。

I just experienced this.我刚刚经历了这一点。 I think, my main problem was tailwind innitialization with npx tailwind init , not npx tailwind init -p (which also generate postcss fileconfig).我认为,我的主要问题是使用 npx tailwind init 进行npx tailwind init ,而不是 npx tailwind npx tailwind init -p (它也生成 postcss 文件配置)。

Another solution so that you can fix the problem in next js is this另一个解决方案,以便您可以在下一个 js 中解决问题是这个

in the tailwind.config.js add this configuration:在 tailwind.config.js 添加这个配置:

/** @type {import('tailwindcss').Config} */
module.exports = {
  purge: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  subject: {
    extend: {},
  },
  plugins: [require("@tailwindcss/typography"),require('@tailwindcss/forms'),],
  
};

and in postcss.config.js在 postcss.config.js 中

module.exports = {
  plugins: ['tailwindcss','postcss-preset-env'],
};

lastly in the next js config you will add this to make it work for you .最后,在下一个 js 配置中,您将添加它以使其适合您

/** @type {import('next').NextConfig} */
const nextConfig = {
  swcMinify: true,
  reactStrictMode: true,
  experimental: {
    concurrentFeatures: false, // <- Set this option to false.
    serverComponents: true,
  },
}

module.exports = nextConfig

and you need creating in styles and adding the style in global.css并且您需要在 styles 中创建并在 global.css 中添加样式

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

I had just migrated my app from CRA .我刚刚从CRA迁移了我的应用程序。 so my CRA App had a folder named features and under it was a folder for each feature was its Redux slicer and componentes, etc.所以我的CRA应用程序有一个名为features的文件夹,在它下面是每个功能的文件夹是它的Redux切片器和组件等。

What solved it for me is to include the features folder in tailwind.config.js :为我解决的问题是将features文件夹包含在tailwind.config.js中:

before:前:

content: [
  "./pages/**/*.{js,ts,jsx,tsx}",
  "./components/**/*.{js,ts,jsx,tsx}",
],

after

content: [
  "./pages/**/*.{js,ts,jsx,tsx}",
  "./components/**/*.{js,ts,jsx,tsx}",
  "./features/**/*.{js,ts,jsx,tsx}",
],

Add a _app.js file inside pages folder then add this code.在 pages 文件夹中添加一个 _app.js 文件,然后添加此代码。 The globals.css path should be correct. globals.css 路径应该是正确的。

import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

After trying everything in this question, what worked was updating nextjs:在尝试了这个问题的所有内容之后,有效的是更新 nextjs:

npm install next@latest npm 安装下一个@latest

Importing like this in the global.css resolved the issue for me:在 global.css 中像这样导入为我解决了这个问题:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Change import to tailwind styles in globals.css by在 globals.css 中将导入更改为顺风 styles

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

instead of代替

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

check if you import the globals.css file on _app.js file if it is not add this检查是否在 _app.js 文件上导入 globals.css 文件,如果它没有添加这个

import '../styles/globals.css'导入'../styles/globals.css'

The issue for me was with a 'create-next-app' I did not have /pages/_app.js and therefore the global.css was not parsed.对我来说,问题在于我没有 /pages/_app.js 的“create-next-app”,因此 global.css 没有被解析。

Creating /pages/_app.js with the following content resolved the issue使用以下内容创建 /pages/_app.js 解决了该问题

import '../styles/globals.css'

// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

See https://nextjs.org/docs/basic-features/built-in-css-supporthttps://nextjs.org/docs/basic-features/built-in-css-support

I have just re-installed my Next.js project and went with Tailwind's guide and it worked!我刚刚重新安装了我的 Next.js 项目并使用了 Tailwind 的指南并且成功了!

Documentation: https://v2.tailwindcss.com/docs/guides/nextjs文档: https://v2.tailwindcss.com/docs/guides/nextjs

After trying everything for 2 hours, just running:在尝试了 2 小时后,只需运行:

npm i tailwindcss@3.0.0

worked for me.为我工作。

This doesn't sound like a sane person's solution, but my solution came down to simply editing globals.css .这听起来不像是正常人的解决方案,但我的解决方案归结为简单地编辑globals.css There is nothing more specific about the solution to share.关于要共享的解决方案,没有什么更具体的了。

I started with a completely fresh Next.js project and followed instructions to add Tailwind CSS. I tried all the solutions listed in this project.我从一个全新的 Next.js 项目开始,并按照说明添加 Tailwind CSS。我尝试了该项目中列出的所有解决方案。

  • Used the example Next.js project creation script (worked)使用示例 Next.js 项目创建脚本(有效)
  • Copied and pasted each file from the example project复制并粘贴示例项目中的每个文件
  • Used the exact same versions使用完全相同的版本
  • Deleted .next and reinstalled all packages删除.next并重新安装所有包
  • Used a variety of different ways to include Tailwind.使用各种不同的方式来包含 Tailwind。

But the precise solution was this: I cut the contents of globals.css such that it only included the @tailwind directives (and some font @import directives above it), which suddenly activated Tailwind CSS. Pasting what I had just cut out maintained this newfound 'working' state.但精确的解决方案是这样的:我剪切了 globals.css 的内容,使其只包含@tailwind指令(以及它上面的一些字体@import指令),这突然激活了 Tailwind CSS。粘贴我刚刚剪切的内容保持这个新发现的“工作”state。

I don't know how this could be, as there shouldn't be anything cached (I deleted the .next build folder) and I had been editing globals.css for other purposes (but I had not touched anything other than the tailwind-related directives).我不知道这是怎么回事,因为不应该有任何缓存(我删除了.next build 文件夹)并且我一直在编辑globals.css用于其他目的(但除了顺风之外我没有触及任何东西 -相关指令)。 It's very mysterious and very annoying.这很神秘,也很烦人。

I hope this might save someone else from tearing their hair out.我希望这可以避免其他人撕掉他们的头发。

for me what was wrong that I unknowingly put spaces in regex.对我来说,我在不知不觉中在正则表达式中放置了空格是怎么回事。 so my code became-所以我的代码变成了-

content: [
"./pages/**/*.{ js, ts, jsx, tsx}",
"./components/**/*.{ js, ts, jsx, tsx}",
],

and this was what causing error.这就是导致错误的原因。 so I again copy pasted from official website.所以我又从官网复制粘贴了。 to make it look like让它看起来像

content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],

I know it was a silly mistake but sometimes you do it unintentionally.我知道这是一个愚蠢的错误,但有时你是无意中犯下的。 :) :)

The problem for me was creating the application via npx create-next-app@latest and opting in for the new src folder structure:我的问题是通过npx create-next-app@latest并选择新的 src 文件夹结构:

? Would you like to use `src/` directory with this project? › No / Yes

If you select Yes , the following addition is required to the tailwind.config.js file:如果你 select Yes ,则需要在tailwind.config.js文件中添加以下内容:

module.exports = {
  content: [
    './src/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};
postcss.config.js postcss.config.js

    module.exports = {
      plugins: {
        tailwindcss: {},
        autoprefixer: {},
      },
    }
tailwind.config.js tailwind.config.js

    module.exports = {
      mode: 'jit',
      content: [
        "./**/*.{js,ts,jsx,tsx}",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
global.css全局.css

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM