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

1

11

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?

enter image description here

enter image description here

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"]
  }
}
Bedabble answered 26/11, 2019 at 16:50 Comment(6)
If you're using webpack to bundle then take a look at #43638954. If not then use webpack (or similar) to bundle and take a look at that question.Luminary
I'm using Parcel, isn't there a way to do this with Parcel?Bedabble
Yes Parcel fills a similar role to webpack so it should just work if you add the type definition for png modulesLuminary
I installed @types/node and edited my tsconfig but it does not seem to be working. Is this the correct way to add type defenitions? I edited the question with the tsconfigBedabble
I found npmjs.com/package/@types/parcel-bundler/v/1.12.0 and installed it but can't find how to set it up anywhere. Do you know how?Bedabble
@types packages don't normally need setting up. Maybe that's not the right oneLuminary
P
19

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.

Puiia answered 26/11, 2019 at 18:23 Comment(2)
where do I create the globals.d.ts?Bedabble
Just create a file somewhere inside your project directory (where tsconfig.json is). TS will grab the file automatically with default include/exclude/files options.Puiia

© 2022 - 2024 — McMap. All rights reserved.