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

React.JS项目执行npm run build编译失败,含ESLint错误求助

解决React构建时的ESLint错误

处理no-use-before-define错误

对应报错:

Line 37:9: 'checkValidServiceWorker' was used before it was defined
no-use-before-define
Line 49:9: 'registerValidSW' was used before it was defined
no-use-before-define

这是因为函数在调用时还未完成定义,有两种解决方法:

  • 调整代码顺序:找到checkValidServiceWorker和registerValidSW的函数声明(通常在src/index.js),将它们移动到调用语句的上方。比如原本是先调用registerValidSW()再写函数定义,调换顺序即可。
  • 修改ESLint规则:在项目根目录的.eslintrc或.eslintrc.json中添加规则配置,允许函数在声明前被调用:
    "rules": {
      "no-use-before-define": ["error", { "functions": false }]
    }
    

处理no-param-reassign错误

对应报错:

Line 59:7: Assignment to property of function parameter 'registration'
no-param-reassign

ESLint禁止直接修改函数参数的属性,可通过以下方式解决:

  • 拷贝参数到局部变量:先复制参数到新变量,再修改局部变量的属性,示例代码:
    function updateServiceWorker(registration) {
      // 浅拷贝参数到局部变量
      const reg = { ...registration };
      // 修改局部变量的属性
      reg.waiting.postMessage({ type: 'SKIP_WAITING' });
    }
    
  • 放宽ESLint规则:在配置文件中允许修改参数的属性:
    "rules": {
      "no-param-reassign": ["error", { "props": false }]
    }
    
  • 重构逻辑:如果是service worker更新场景,可通过postMessage传递指令,避免直接修改registration的属性。

调整完成后,重新执行npm run build即可完成生产构建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:46:16