Next.js的tailwindcss如何全局配置?

nextjs创建项目,使用src目录、使用tailwindcss

npx create-next-app@latest
  1. 修改src/app/page.tsx内容为如下代码,运行项目,访问http://localhost:3000/可以看到tailwindcss是生效的,覆盖了h1的默认样式

    import Link from "next/link";
    
    export default function Home() {
      return (
       <h1>Homepage</h1>
      );
    }
  2. 创建src/pages目录
  3. 创建src/pages/my-test/demo.tsx文件,内容如下,访问http://localhost:3000/my-test/demo发现tailwindcss没有生效

    export default function MyTestDemo() {
      return (
       <h1>Demo</h1>
      );
    }

问题:网上教程能试的都试过了,没有一个是全局生效的,难道要在每个页面都手动引入globals.css吗?还是我的项目结构有问题(src不能和pages一起用)?

问题补充

在创建模板时选择使用src目录,会得到不同的项目结构,此时模板目录如下:

/src
  /app
    - favicon.ico
    - globals.css
    - layout.tsx
    - page.tsx
- tailwind.config.js
  1. tailwind.config.ts文件内容如下,模板已经配置好

    import type { Config } from "tailwindcss";
    
    export default {
      corePlugins: {
     preflight: true,
      },
      content: [
     "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
     "./src/components/**/*.{js,ts,jsx,tsx,mdx}",
     "./src/app/**/*.{js,ts,jsx,tsx,mdx}",
      ],
      theme: {
     extend: {
       colors: {
         background: "var(--background)",
         foreground: "var(--foreground)",
       },
     },
      },
      plugins: [],
    } satisfies Config;
  2. /src/app/globals.css文件已注入

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    :root {
      --background: #ffffff;
      --foreground: #171717;
    }
    
    @media (prefers-color-scheme: dark) {
      :root {
     --background: #0a0a0a;
     --foreground: #ededed;
      }
    }
    
    body {
      color: var(--foreground);
      background: var(--background);
      font-family: Arial, Helvetica, sans-serif;
    }
  3. /src/app/layout.tsx文件中模板已经引入global.css

    ...
    import "./globals.css";
    ...
    
    export default function RootLayout({
      children,
    }: Readonly<{
      children: React.ReactNode;
    }>) {
      return (
     <html lang="en">
       <body
         className={`${geistSans.variable} ${geistMono.variable} antialiased`}
       >
         {children}
       </body>
     </html>
      );
    }
  4. /src/app/page.tsx内容即为http://localhost:3000/的显示内容,tailwindcss生效
  5. 新增/src/pages/my-test/demo.tsx文件,访问http://localhost:3000/my-test/demo发现tailwindcss不生效

问题

  • 每个页面都引入global.css吗?这明显不太对劲
  • 或者有什么配置可以让每个src/pages目录中的页面都调用src/app/layout.tsx
阅读 1.3k
3 个回答

完全没有遇到类似的问题,建议把完整的项目脚手架放出来看看。

其它建议:

  1. 确认版本号。最近发布的 tailwindcss 是 v4,如果你看的是老教程,那很可能不对。
  2. 找一个参考项目,照抄过来。记得版本号要一模一样。没记错的话 Vercel 官方做过很多可以参考的项目。
新手上路,请多包涵

文档 客户端的要配置一下

新手上路,请多包涵

新增页面 /src/pages/my-test/demo.tsx 应该改为 /src/app/my-test/page.tsx

app-router 新增页面必须放到 app 目录下 建议阅读文档路由相关章节

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题