nextjs使用antd后启动报错问题

环境

  • nextjs version: 14.2.8

  • antd version: 5.20.5

问题及解决

问题

开始 NextJS 的入手 demo, npx install antd --save 后,在 pages/index.tsc 中使用:

1
2
3
4
5
6
7
8
9
10
import { Button } from 'antd';


export default function Page() {

<div className="App">
<Button type="primary">Button</Button>
</div>
return <h1>Hello, Next.js!</h1>
}

npm run build 报错

如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   Collecting page data  ./Users/ayal/us-dev/projects/next/cms/node_modules/rc-util/es/omit.js:1
export default function omit(obj, fields) {
^^^^^^

SyntaxError: Unexpected token 'export'
at internalCompileFunction (node:internal/vm:128:18)
at wrapSafe (node:internal/modules/cjs/loader:1279:20)
at Module._compile (node:internal/modules/cjs/loader:1331:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
at Module.load (node:internal/modules/cjs/loader:1205:32)
at Module._load (node:internal/modules/cjs/loader:1021:12)
at Module.require (node:internal/modules/cjs/loader:1230:19)
at mod.require (/Users/ayal/us-dev/projects/next/cms/node_modules/next/dist/server/require-hook.js:65:28)
at require (node:internal/modules/helpers:179:18)
at 3998 (/Users/ayal/us-dev/projects/next/cms/.next/server/pages/index.js:1:788)

原因及解决

翻了一下版本内容,大概原因是 构建工具无法识别 es 模块,需要将 antd (其他第三方库如果遇到该问题处理方法类似)加入
next.config.mjs -> nextConfig.transpilePackages 中, 如下:

1
2
3
4
5
6
7
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: [ "antd", "@ant-design", "rc-util" ],
};

export default nextConfig;

参考