NextJS项目生产构建失败求助(开发模式运行正常)
Next.js生产构建失败:Type 'OmitWithTag<InputProps...>' 类型错误
问题场景
开发模式下NextJS项目运行正常,但执行生产构建(next build)时抛出以下类型错误:
Type error: Type 'OmitWithTag<InputProps, keyof PageProps, "default">' does not satisfy the constraint '{ [x: string]: never; }'.
Property 'name' is incompatible with index signature.
Type 'string' is not assignable to type 'never'.
对应的Input组件代码:
import React, {KeyboardEvent} from 'react' interface InputProps{ name: string, id: string, placeholder: string, onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void; } const Input = (props: InputProps) => { const {name, id, placeholder, onKeyDown} = props return ( <input name={name} id={id} placeholder={placeholder} onKeyDown={onKeyDown} type="text" className="bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" required /> ) } export default Input
问题原因
你大概率是在Next.js的页面文件(page.tsx/page.jsx)中直接导出了这个Input组件。Next.js对页面组件的Props有严格约束:页面组件只能接收Next.js内置的PageProps,不能自定义额外的props,生产构建时的类型检查会拦截这种不符合规范的导出。
解决方法
方案1:抽离组件到独立文件(推荐)
把Input组件单独放到一个非页面文件中,比如components/Input.tsx,然后在页面文件中导入使用:
- 创建
components/Input.tsx,放入上述Input组件代码 - 在页面文件(比如
app/page.tsx)中导入并使用:
import Input from '@/components/Input'; export default function Home() { return ( <div> <Input name="username" id="username" placeholder="请输入用户名" /> </div> ) }
方案2:页面内嵌套定义(不推荐,不利于组件复用)
如果一定要在页面文件里定义Input组件,不要单独导出它,把它作为页面组件的内部嵌套组件:
import React, {KeyboardEvent} from 'react' interface InputProps{ name: string, id: string, placeholder: string, onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void; } // 页面组件只导出默认的Home组件,Input作为内部组件 export default function Home() { const Input = (props: InputProps) => { const {name, id, placeholder, onKeyDown} = props return ( <input name={name} id={id} placeholder={placeholder} onKeyDown={onKeyDown} type="text" className="bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" required /> ) } return ( <div> <Input name="username" id="username" placeholder="请输入用户名" /> </div> ) }
完成以上修改后,重新执行next build即可正常完成生产构建。
内容的提问来源于stack exchange,提问作者Certa Yustitia
相关产品推荐
相关产品推荐

