nextjs创建项目,使用src
目录、使用tailwindcss
。
npx create-next-app@latest
修改
src/app/page.tsx
内容为如下代码,运行项目,访问http://localhost:3000/
可以看到tailwindcss
是生效的,覆盖了h1
的默认样式import Link from "next/link"; export default function Home() { return ( <h1>Homepage</h1> ); }
- 创建
src/pages
目录 创建
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
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;
/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; }
/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> ); }
/src/app/page.tsx
内容即为http://localhost:3000/
的显示内容,tailwindcss
生效- 新增
/src/pages/my-test/demo.tsx
文件,访问http://localhost:3000/my-test/demo
发现tailwindcss
不生效
问题
- 每个页面都引入
global.css
吗?这明显不太对劲 - 或者有什么配置可以让每个
src/pages
目录中的页面都调用src/app/layout.tsx
?
完全没有遇到类似的问题,建议把完整的项目脚手架放出来看看。
其它建议: