nextjs V13 router模式 tailwindcss 只使用dark模式
要在Next.js v13中使用路由模式和Tailwind CSS的暗模式,首先需要安装所需的依赖项。
- 在终端中导航到你的Next.js项目的根目录。
- 运行以下命令来安装所需的依赖项:
npm install next react-router-dom tailwindcss twin
接下来,我们将配置Next.js和Tailwind CSS。
- 在根目录中创建一个名为
.babelrc的文件,并添加以下内容:
{
"presets": ["next/babel"]
}
- 创建一个名为
tailwind.config.js的文件,并将以下内容添加到文件中:
module.exports = {
mode: 'jit',
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: 'class',
theme: {
extend: {},
},
variants: {},
plugins: [],
}
- 创建一个名为
postcss.config.js的文件,并将以下内容添加到文件中:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
- 在根目录中创建一个名为
styles的文件夹,并在该文件夹中创建一个名为globals.css的文件。在globals.css文件中添加以下内容:
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
html,
body {
background-color: #f9fafb;
}
.dark {
@apply dark;
}
.dark body {
background-color: #1f2937;
color: #fff;
}
现在我们将配置路由。
- 在
pages文件夹中创建一个名为_app.js的文件,并将以下内容添加到文件中:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { ThemeProvider } from 'next-themes';
import 'tailwindcss/tailwind.css';
function MyApp({ Component, pageProps }) {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url) => {
document.documentElement.classList.remove('dark');
document.documentElement.classList.add('light');
};
router.events.on('routeChangeStart', handleRouteChange);
return () => {
router.events.off('routeChangeStart', handleRouteChange);
};
}, []);
return (
<ThemeProvider attribute="class">
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
在上面的代码中,我们使用了next-themes库和ThemeProvider组件来处理暗模式。在路由更改时,我们将document.documentElement的类从dark更改为light,以确保我们在切换页面时正确应用暗模式。
现在你可以在你的页面组件中使用Tailwind CSS类来应用样式了。
import React from 'react';
const Home = () => {
return (
<div className="p-4">
<h1 className="text-2xl font-bold">Welcome to Next.js + Tailwind CSS</h1>
<p className="text-gray-500">This is a sample page.</p>
</div>
);
};
export default Home;
这就是在Next.js v13中使用路由模式和Tailwind CSS的暗模式的基本配置。你现在可以根据自己的需求进行调整和添加更多样式
原文地址: http://www.cveoy.top/t/topic/iWYj 著作权归作者所有。请勿转载和采集!