【问题标题】:Ignore "cannot find module" error on typescript忽略打字稿上的“找不到模块”错误
【发布时间】:2023-03-20 20:29:01
【问题描述】:

Typescript 编译器能否忽略导入表达式中的cannot find module 'x' 错误,例如:

//How to tell the compiler that this module does exists
import sql = require('sql');

有多个 npm 库,例如 node sql,它们没有现有的类型

除了用declare module x ... 创建一个新的定义文件之外,有没有办法告诉编译器忽略这个错误?

【问题讨论】:

    标签: import module typescript


    【解决方案1】:

    从 TypeScript 2.6(2017 年 10 月 31 日发布)开始,现在有 a way to ignore all errors from a specific line 在目标行之前使用 // @ts-ignore cmets。

    The mendtioned documentation 已经够简洁了,但要回顾一下:

    // @ts-ignore
    const s : string = false
    

    禁用此行的错误报告。

    但是,只有在修复错误或使用像 (x as any) 这样的黑客手段比丢失所有类型检查更麻烦时,才应将其用作最后的手段。

    至于指定某些错误,目前(2018年中)状态讨论here, in Design Meeting Notes (2/16/2018) and further comments,基本是

    “没有结论

    强烈反对引入这种微调。

    【讨论】:

      【解决方案2】:

      如果你只是想绕过编译器,你可以为那个模块创建一个 .d.ts 文件,例如,你可以创建一个 sql.d.ts 文件,里面有这个:

      declare module "sql" {
        let _sql: any;
        export = _sql;
      }
      

      【讨论】:

      • 嗨,请问这个模块的声明是什么样子的:github.com/christophergregory/shopify-node-api/blob/master/lib/… 我尝试声明它,但我得到了Invalid module name in augmentation, module 'shopify-node-api' cannot be found.
      • 如果不为每个模块创建单独的虚拟定义文件,是否有其他方法可以绕过这些错误?
      • 这也没用。我收到了这个错误:Invalid module name in augmentation. Module 'express' resolves to an untyped module at '.../node_modules/express/index.js', which cannot be augmented
      • 如果导入是@foo/bar 导入,这种方法如何工作?
      【解决方案3】:

      解决了这个问题 默认情况下,@ts-check 查找模块的定义,无论是您自己的代码还是外部库。

      既然我们没有使用 ES6 风格的模块,那么我们必须使用 commonjs,请查看我的 jsconfig.json 文件以获取帮助。

      {
        "compilerOptions": {
          "target": "es6",
          "module": "commonjs",
          "lib": ["es5", "es6", "es7"]
        },
        "include": ["src/**/*"],
        "exclude": ["node_modules"],
        "typeAcquisition": { "enable": true }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-05
        • 2019-12-21
        • 2014-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多