You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Next.js至12.x.x并添加TypeScript后构建报错

解决Next.js 12构建时TypeScript interface解析错误问题

问题描述

将Next.js应用从10.x升级到12.x并引入TypeScript后,开发环境运行正常,但执行yarn next build时出现以下错误:

./src/components/Header.tsx
7:1 Error: Parsing error: The keyword 'interface' is reserved

问题原因

  1. ESLint未正确配置为解析TypeScript文件,导致把.tsx中的TypeScript语法(如interface)当作无效JavaScript语法处理
  2. tsconfig.json中存在与Next.js默认编译流程冲突的配置项
  3. Header组件的props接收方式不符合React组件规范

解决方案

1. 配置ESLint支持TypeScript

首先安装TypeScript相关的ESLint依赖:

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

在项目根目录创建或修改.eslintrc.json:

{
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "extends": [
    "next/core-web-vitals",
    "plugin:@typescript-eslint/recommended"
  ]
}

2. 优化tsconfig.json配置

Next.js自带默认TypeScript配置,移除与Next编译流程冲突的配置项,修改后的配置如下:

{
  "compilerOptions": {
    "target": "es2016",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "noEmit": true,
    "incremental": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

移除了rootDir、outDir、sourceMap、removeComments、noEmitOnError、module这些Next.js会自动处理的配置项

3. 修复Header组件的props写法错误

React组件接收的是props对象,而非单个参数,修改组件定义:

// Header.tsx
import React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';

import config from '../config';

interface HeaderProps {
    home: boolean;
}

// 解构props对象获取home属性
const Header = ({ home }: HeaderProps) => (
    <Box
        sx={{
            flexShrink: 0,
            paddingTop: home ? '15rem' : '0'
        }}>
        <Typography
            component="h1"
            sx={{
                fontSize: '2.5rem !important',
                lineHeight: 1.2,
                fontWeight: 800,
                letterSpacing: '-0.05rem',
                textAlign: 'center'
            }}>
            {config.name}
        </Typography>
        <Typography
            sx={{
                marginTop: '1rem',
                lineHeight: 1.2,
                letterSpacing: '-0.05rem',
                textAlign: 'center'
            }}>
            {config.title}
        </Typography>
    </Box>
);

export default Header;

4. 重新执行构建

完成以上修改后,重新运行构建命令:

yarn next build

内容的提问来源于stack exchange,提问作者bonum_cete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:09:22