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

TypeScript编译生成__rest变量引发ESLint import/first错误

问题原因

TypeScript编译带默认值的解构+rest参数时,会自动生成__rest辅助函数并内联到编译后的JS文件顶部,而React的JSX runtime import被放在这个函数之后,违反了ESLint import/first规则(要求所有import必须位于模块代码最前面)。

解决方法

方法1:调整组件写法,避免生成__rest函数

不用在函数参数里同时写默认值和rest解构,改为直接解构所有props并处理默认值,这样TS不会生成__rest辅助函数:

type ButtonTestProps = {
  style?: string;
  label: string;
};

export function ButtonTest(props: ButtonTestProps) {
  // 直接解构所有需要的props,单独处理默认值
  const { style = "border", label } = props;
  return (
    <button className={style === "border" ? "border-4 border-blue" : ""}>
      {label}
    </button>
  );
}

编译后的JS文件会把import放在最顶部,不再触发ESLint错误。

方法2:配置TypeScript使用外部辅助函数

让TypeScript从tslib包导入辅助函数,而不是内联生成:

  1. 安装tslib依赖:
npm install tslib --save
  1. 修改tsconfig.json,启用importHelpers选项:
{
  "compilerOptions": {
    "importHelpers": true,
    // 其他已有配置...
  }
}

配置后,编译后的JS会先导入tslib的__rest,再导入React的JSX runtime,所有import都在文件顶部,符合ESLint规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 06:52:47