【问题标题】:Typescript image import打字稿图像导入
【发布时间】:2018-12-08 13:40:53
【问题描述】:

我在这里找到了解决方案:Webpack & Typescript image import

但是我收到了错误:

[ts]
Types of property 'src' are incompatible.
  Type 'typeof import("*.png")' is not assignable to type 'string | undefined'.
    Type 'typeof import("*.png")' is not assignable to type 'string'.

我想我需要以某种方式强制导入,但不知道如何。 我在 React 中这样做。我看到src 属性被定义为string | undefined,这就是弹出错误的原因。

代码如下:

import * as Logo from 'assets/images/logo.png';

HTML:

<img src={Logo} alt="" />

以及基于上述解决方案的定义:

declare module "*.png" {
  const value: string;
  export default value;
}

Tsconfig:

{
  "compilerOptions": {
    "baseUrl": "./",
    "jsx": "react",
    "lib": ["es5", "es6", "dom"],
    "module": "commonjs",
    "noImplicitAny": false,
    "outDir": "./dist/",
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "typeRoots": [
      "custom_typings"
    ]
  },
  "include": ["./src/**/*.tsx"],
  "exclude": ["dist", "build", "node_modules"]
}

【问题讨论】:

  • 根据here,您应该使用 require 而不是 import。所以它应该是这样的:const Logo = require('assets/images/logo.png')
  • 是的,我看到了。但这不是这样做的优雅方式。问题是,当您执行import 时,它会在您加载应用程序时起作用。但是你得到 lint 错误。
  • import 有效,因此应该使用它。 @MarioPetrovic 默认导入没有名称。这就是您可以省略 * as 部分的原因。 import Logo from './logo.jpg' 很好,因为它等同于 const Logo = require(./logo.jpg)

标签: reactjs typescript module tsconfig react-tsx


【解决方案1】:

消除该错误的方法之一是修改 d.ts 文件,如下所示:

declare module "*.png"

删除

{
  const value: string;
  export default value;
}

或者你也可以这样做:

declare module "*.png" {
  const value: any;
  export default value;
}

更新

类型检查的最佳解决方案是:

declare module "*.png" {
   const value: any;
   export = value;
}

【讨论】:

  • 已经尝试从 string 修改为 any 并没有帮助。解析导入类型时似乎没有考虑 const 值。至于删除块,它也不会起作用。
  • 我得到:TS1192:模块 '"*.png"' 没有默认导出。
  • @danielrvt 你可能没有在d.ts / custom.d.ts 上这样做,但在其他地方......
  • 由于this long-standing issue,我无法使其正常工作。一旦我将通配符 declare module 语句移动到他们自己的类型文件中,而不是现有的 globals.d.ts 用于其他东西(这发生在 import 接口声明......),我就能够@987654333 @.
  • .d.ts 文件需要放入 src/ 文件夹才能正常工作,以防其他人在将其放入项目根目录时遇到该问题。
【解决方案2】:

对于react-native

在项目root 文件夹上创建global.d.ts 文件,然后在此处添加下一行

declare module '*.png' {
  const value: import('react-native').ImageSourcePropType;
  export default value;
}

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 2023-02-09
    • 2021-04-21
    • 2012-12-26
    • 1970-01-01
    • 2016-06-17
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多