【问题标题】:False positive Typescript cannot find module warning误报 Typescript 找不到模块警告
【发布时间】:2019-01-14 10:31:58
【问题描述】:

我正在使用以下代码导入图标:

import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg"

在 Visual Studio Code 1.25.1 中,我从 tslint 收到以下警告:

[ts] 找不到模块 '!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg'。

即使我应用 tslint 忽略语句,我仍然会收到此警告:

// tslint:disable-next-line:no-implicit-dependencies

导入工作正常(即 WebPack 构建包时没有错误),但我真的很想摆脱这个警告。有什么想法吗?

【问题讨论】:

  • 从 import 调用 loader 是不寻常的......也许对所有 loader 模块和规则使用 webpack 会更好。
  • 您可以使用// @ts-ignore 忽略该错误。
  • 在您的代码中是否有 Icon 导入的任何实际用例?否则,您可以直接导入文件,我从未见过除了节点模块(或 commonjs .. 或其他任何东西)之外使用过这种导入,我总是看到 webpack 直接导入打字稿而没有“模块化”方式(其中抛出一个公平的错误,因为我真的怀疑在这种情况下是否存在默认导出)。
  • @briosheje 我正在使用github.com/jhamlet/svg-react-loader,它使用了我也发现的新导入样式。即使为此加载程序设置了 webback,导入仍然是“奇怪的”。
  • @HardikModha 即使设置了“// @ts-ignore”,警告仍然显示在 VS Code 中。该代码使用 WebPack 构建良好,没有警告,所以我认为它是 VS Code 中的 TSLint 扩展问题?

标签: javascript typescript webpack tslint svg-react-loader


【解决方案1】:

要解决此问题,请在存储库的根目录中创建文件 types/images.d.ts,其中包含以下内容:

declare module '*.svg' {
  import React from 'react';

  interface SVGProps {
    className?: string,
    width?: number,
    height?: number,
  }

  class SVG extends React.Component<SVGProps> {}

  export default SVG;
}

【讨论】:

  • 请考虑这种类型:React.Component&lt;HTMLAttributes&lt;SVGElement&gt;&gt;
【解决方案2】:

要获得 tslint,您可以这样做

import MyIcon from '!svg-react-loader?name=Icon!./down-arrow.svg'

在你的 tslint.conf 中使用它

{
  "rules": {
    "no-implicit-dependencies": [
      true,
      ["!svg-react-loader?name=Icon!."]
    ]
  }
}

这有点乱,但它确实有效。本质上,您需要将整个加载程序字符串列入白名单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2016-09-20
    • 2020-08-15
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多