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

在TypeScript中将require替换为import遇ESLint及TS7016错误的解决方法

解决方案

针对你遇到的ESLint禁止require、但import又找不到类型声明的问题,给你几个可行的解决办法:

1. 补充旧包的TypeScript声明文件

  • 安装社区类型包:如果该旧包有社区维护的类型声明,直接安装对应的@types包:
    npm install @types/xxx --save-dev
    # 或者用yarn
    yarn add @types/xxx -D
    
  • 自定义声明文件:如果没有现成的@types包,在项目中新建一个类型声明文件(比如src/types/xxx.d.ts),内容写:
    declare module 'xxx';
    
    然后在tsconfig.json里配置typeRoots,让TypeScript识别这个自定义类型文件夹:
    {
      "compilerOptions": {
        "typeRoots": ["./node_modules/@types", "./src/types"]
      }
    }
    

2. 让ESLint允许特定场景的require

  • 单行忽略:在需要用require的代码行上方添加ESLint忽略注释:
    // eslint-disable-next-line @typescript-eslint/no-require-imports
    const xxx = require('xxx');
    
  • 全局规则配置:在.eslintrc(或.eslintrc.json)里修改规则,允许指定模块使用require:
    {
      "rules": {
        "@typescript-eslint/no-require-imports": ["error", { "allow": ["xxx"] }]
      }
    }
    

3. 使用动态import(异步场景适用)

如果该模块的使用不影响应用初始化,可以用动态import来规避类型问题,同时符合ES模块规范:

import('xxx').then((module) => {
  const xxx = module.default || module;
  // 在这里使用xxx
});

注意要确保tsconfig.json里的module配置为ESNext或CommonJS,支持动态import语法。

4. 调整TypeScript配置适配混合模块

在tsconfig.json里开启相关配置,兼容CommonJS模块:

{
  "compilerOptions": {
    "allowJs": true,
    "moduleResolution": "node"
  }
}

allowJs允许项目中混合JavaScript和TypeScript文件,moduleResolution: 'node'让TypeScript按照Node.js的模块解析规则处理模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:42:36