Typescript - How can I import png files into my typescript file?

为君一笑 提交于 2019-12-11 14:31:16

问题


I put up my own typescript project with the Parcel compiler and got everything running on the built-in server. I implemented pixi.js and wanted to import .png files into my .ts files. But when I try to import it says it can't find the module, even tho both files are in the same folder? What am I missing?

I tried to do the following

npm install @types/node --save-dev

tsconfig.json (located in my root folder)

{
  "compilerOptions": {
    "types": ["node"],
    "typeRoots": ["node_modules/@types"]
  }
}

回答1:


As far as I can guess from your given example, this does not have anything to do with Parcel.

Parcel v1 will internally invoke tsc and the compiler will simply emit an error for unknown file extensions like .png, because pure TS projects will only be able to import code files (.js,.ts, .tsx, .jsx or .json) without a module bundler like Parcel or Webpack involved.

Bundlers allow to import other file types by converting them into valid modules that can be consumed in your project (implemented by loaders in Webpack, Parcel does handle it even more transparently).

In order to "convince" the compiler, that these sorts of imports are fine and to make the module known, wildcard module declarations can be used. For example to make .png file imports compile, you create a file globals.d.ts or similar with following declaration:

declare module '*.png';

That already should be enough to satisfy the compiler (here is a Parcel specific related issue).

Hope, it helps.



来源:https://stackoverflow.com/questions/59055755/typescript-how-can-i-import-png-files-into-my-typescript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!