使用在Typescript中导入的图像

时间:2018-10-03 02:38:04

标签: typescript webpack

我正在使用Typescrip,Three.js和Webpack创建一个项目。

对于这个项目,我需要在视图内放置一个图标以全屏显示它。

要实现这一点,我遵循了上述线程: Typescript image import

我的 import-png.d.ts

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

我的图像导入:

import * as fullscreenIcon from "./resources/fullscreenIcon.png";

我添加图标的功能:

private addFullscreenIcon(): void {
   const fullscreen = document.createElement("div");
   const icon = document.createElement("img") as HTMLImageElement;

   console.log("fullscreen", fullscreenIcon);

   icon.src = fullscreenIcon.default;
   fullscreen.appendChild(icon);

   this.canvas.append(fullscreen);
}

在页面控制台上,我得到了:

Console error

我的html结构是const fullscreen = document.createElement("div");命令生成的div,它是:

enter image description here

我捆绑的文件夹结构是这样的:

Folder structure

在控制台中,图像名称为627aac9ac2a7a147efb902c908a25b2c.png,但在文件夹结构中为fullscreenIcon.png

因此,如果icon.src = fullscreenIcon.default;无法正常工作,该怎么办?

1 个答案:

答案 0 :(得分:1)

file-loader生成一个具有CommonJS导出分配而不是默认导出的模块。启用esModuleInterop TypeScript编译器选项以使导出分配可与默认导出互操作,或将声明更改为:

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

,然后从您的代码中删除.default。有关不同种类的进出口的一些背景知识,请参阅this answer(虽然它不涵盖TypeScript)。