NextJS无法编译TypeScript 5特性,如何更新其转译器?
问题:NextJS(SWC)无法转译TypeScript 5特性,构建报错
已将TypeScript版本更新至5.0.2,但使用SWC作为转译器的NextJS在构建时,遇到TS 5特性(如const泛型参数)报错,而tsc编译正常。
示例代码
type fun = <const T>() => {};
终端报错输出
tsc // 编译正常 ... next build Error: x Expected ',', got 'T' ,---- 7 | type fun = <const T>() => {}; : ^ `---- Caused by: 0: failed to process input file 1: Syntax Error
已尝试的方法
在package.json中添加resolutions字段强制指定TypeScript版本:
"resolutions": { "typescript": "5.0.2" }
解决方案
1. 升级Next.js到支持TypeScript 5的版本
Next.js 13.4及以上版本正式支持TypeScript 5.x,旧版本的内置SWC转译器不兼容TS5的新语法。执行以下命令升级:
# npm npm install next@latest react@latest react-dom@latest # yarn yarn add next@latest react@latest react-dom@latest # pnpm pnpm update next react react-dom --latest
2. 移除不必要的resolutions配置
Next.js对TypeScript版本有官方兼容范围,强制通过resolutions指定TS版本可能导致SWC与TS版本不匹配。升级Next.js后,直接安装对应兼容的TS版本即可:
npm install typescript@^5.0.2
3. 清除Next.js缓存
缓存可能残留旧的转译配置,执行以下命令清除缓存后重新构建:
npx next clean next build
4. 检查SWC配置(可选)
如果升级后仍有问题,确认next.config.js中没有禁用SWC的TypeScript转译,或者存在配置冲突:
/** @type {import('next').NextConfig} */ const nextConfig = { swcMinify: true, // 确保SWC压缩启用(默认开启) typescript: { ignoreBuildErrors: false, // 不要忽略TS构建错误,方便排查 }, }; module.exports = nextConfig;
内容的提问来源于stack exchange,提问作者austin
相关产品推荐
相关产品推荐

