nextjs 集成 antd 踩坑&指南

前言

最近在重构 Open-Job 的前端项目,打算使用 Nextjs + Antd 实现,这样做的好处就是容易升级,而且也不用管路由什么的,废话不多说,我们直接进入主题。

使用的版本如下:

  • Nextjs 版本:14.0.3
  • Antd 版本:5.11.5

坑一:项目引入 Antd 组件之后启动报错

项目初始化完之后我在 index.tsx 页面引入了 antd 的 Layout 相关组件(注意,这时不管你在页面中引入 antd 的哪个组件启动项目都会报错的),启动项目之后报错信息如下:

SyntaxError: Cannot use import statement outside a module

没错,就是这个报错它盘了我一晚上,直到第二天才找到答案💀🤮

解决方法就是在 next.config.js 中配置 transpilePackages,就像下面这样就 OK 了。

js 复制代码
const nextConfig = {  
    reactStrictMode: true,  
    transpilePackages: ['antd']  
};  
  
module.exports = nextConfig;

你可能会问 transpilePackages 是个啥,问的好,看 这里 就好,这是它的官方文档。

Next.js can automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (node_modules). This replaces the next-transpile-modules package.

翻译过来就是说:

Next.js 可以从本地软件包(如 monorepos)或外部依赖(node_modules)自动转译和捆绑依赖。这将取代 next-transpile-modules 软件包。

注意是 v13.0.0 才增加的,也就是小于这个版本的需要添加 next-transpile-modules 依赖才能实现上述的效果。

如果后面你还集成了 @ant-design/icons,还是上面的步骤,代码如下

js 复制代码
const nextConfig = {  
reactStrictMode: true,  
transpilePackages: ['antd', '@ant-design/icons'],  
};  
  
module.exports = nextConfig;

坑二: antd 和 tailwind 样式冲突

在我的页面中放了一个 antd 的 Button 按钮

html 复制代码
<Button type='primary'>Button</Button>

但是这个按钮只有当我 hover 的时候才能看到

最后无奈,只好先去掉了 tailwind ☹

指南:安装 @ant-design/cssinjs

可能有人会问为什么需要安装这个?

来,上答案

从 antd 的 官方文档 得知,为了让 antd 组件库在你的 Next.js 应用中能够更好的工作,提供更好的用户体验,你可以尝试使用下面的方式将 antd 首屏样式按需抽离并植入到 HTML 中,以避免页面闪动的情况。那么你需要按照它的文档一步一步来就行,由于我是用的 Pages Router,所以这里的截图是这个,你要根据你的实际情况操作。

注意它说的版本一致(Tips),我这里需要安装的版本是 @ant-design/cssinjs": "^1.18.0

指南:实现动态主题

先来张效果图瞄一眼

老规矩,我们先看官方文档有没有

在 Antd 5.x版本中,如果想实现动态主题切换(默认主题切换与暗色主题),有一种更加简单的方案,就是借助于 ConfigProvider

参考ConfigProvider的API,会发现其中有一个theme的属性,

再根据介绍中跳转至定制主题,仔细阅读会惊喜的发现以下说明:

也就是说,只要我们通过修改算法就可以实现动态主题切换了,好了,那我们开始实操。

  1. 编写 useTheme.ts
ts 复制代码
import { useEffect, useState } from 'react';

const useTheme = (): [string, (value: string) => void] => {
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    const storeTheme = window.localStorage.getItem('theme');
    if (storeTheme) setTheme(storeTheme);
  }, []);

  const setValue = (value: string) => {
    setTheme(value);
    window.localStorage.setItem('theme', value);
  };

  return [theme, setValue];
};

export default useTheme;
  1. 使用 useTheme 和 ConfigProvider
tsx 复制代码
import { Layout, Menu, ConfigProvider, theme } from 'antd';  
const { Content, Sider } = Layout;  
  
const BaseLayout = ({ children }: any) => {  
    const router = useRouter();  
    const cleanedPath = router.asPath.split(/[\?\#]/)[0];  
    const [collapsed, setCollapsed] = useState(false);  
    const [value, setValue] = useTheme();  
  
    // 收起的宽度  
    const collapsedWidth = 64;  

    const siderWidth = 208;  
  
return (  
    <ConfigProvider  
        theme={{  
        algorithm:  
        value === 'light' ? theme.defaultAlgorithm : theme.darkAlgorithm,  
        }}  
    >  
        <Layout style={{ minHeight: '100vh' }}>  

        </Layout>  
    </ConfigProvider>  
    );  
};  
  
export default BaseLayout;

剩下的就是写个按钮去改 value 的值即可,听说你想看看源码,好,上链接:

github.com/lijunping36...

感谢老铁的三连🤞

相关推荐
gnip3 分钟前
项目开发流程之技术调用流程
前端·javascript
转转技术团队17 分钟前
多代理混战?用 PAC(Proxy Auto-Config) 优雅切换代理场景
前端·后端·面试
南囝coding18 分钟前
这几个 Vibe Coding 经验,真的建议学!
前端·后端
gnip32 分钟前
SSE技术介绍
前端·javascript
yinke小琪1 小时前
JavaScript DOM节点操作(增删改)常用方法
前端·javascript
枣把儿1 小时前
Vercel 收购 NuxtLabs!Nuxt UI Pro 即将免费!
前端·vue.js·nuxt.js
望获linux1 小时前
【Linux基础知识系列】第四十三篇 - 基础正则表达式与 grep/sed
linux·运维·服务器·开发语言·前端·操作系统·嵌入式软件
爱编程的喵1 小时前
从XMLHttpRequest到Fetch:前端异步请求的演进之路
前端·javascript
喜欢吃豆1 小时前
深入企业内部的MCP知识(三):FastMCP工具转换(Tool Transformation)全解析:从适配到增强的工具进化指南
java·前端·人工智能·大模型·github·mcp
Thomas游戏开发1 小时前
Unity3D Boehm GC原理解析
前端框架·unity3d·游戏开发