代码之家  ›  专栏  ›  技术社区  ›  Mario Petrovic Emmanuel Onah

类型脚本图像导入

  •  4
  • Mario Petrovic Emmanuel Onah  · 技术社区  · 8 年前

    我在这里找到了一个解决方案: 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'.
    

    我想我需要以某种方式强制导入,但不知道怎么做。 我这么做是为了回应。我看到了 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;
    }
    

    t配置:

    {
      "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"]
    }
    
    1 回复  |  直到 8 年前
        1
  •  11
  •   Piyush Zalani    8 年前

    消除该错误的方法之一是按如下方式修改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;
    }
    
    推荐文章