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

React项目中使用TypeScript as const语法时出现缺少分号错误

「Syntax error: Missing semicolon」错误排查与修复

问题分析

你编写的TypeScript代码本身语法是正确的,出现分号缺失错误,本质是项目的编译/代码校验工具没有正确识别TypeScript的as const断言语法,将其误判为不符合规则的JavaScript代码。

修复方案

1. 确认TypeScript编译配置正确

  • 项目根目录必须存在tsconfig.json,若没有则执行命令生成:
    npx tsc --init
    
  • 确保tsconfig.json的编译目标支持现代语法,示例配置:
    {
      "compilerOptions": {
        "target": "ES2015",
        "module": "ESNext",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true
      },
      "include": ["src/**/*"]
    }
    

2. 修正ESLint配置(若使用ESLint)

如果项目用ESLint做代码校验,必须配置TypeScript解析器:

  • 先安装依赖:
    npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
    
  • 在.eslintrc.js中更新配置:
    module.exports = {
      root: true,
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended'
      ],
      rules: {
        // 统一分号规则,避免误报
        'semi': ['error', 'always'],
        '@typescript-eslint/semi': ['error', 'always']
      }
    };
    

3. 配置Babel支持TypeScript(若使用Babel)

如果项目用Babel处理代码,需要添加TypeScript预设:

  • 安装依赖:
    npm install @babel/preset-typescript --save-dev
    
  • 在babel.config.json中添加预设:
    {
      "presets": [
        "@babel/preset-react",
        "@babel/preset-typescript"
      ]
    }
    

4. 快速验证:检查相邻代码

有时候错误提示的位置不准确,检查该文件中这段代码的前后部分,是否存在真正缺失分号或者语法不规范的JavaScript代码,修复后再重新运行项目。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:19:20