Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to use "require" instead of "import from" for an image in React?

I see that this answer suggests the syntax for importing images as shown below (commented out). In my case, it didn't work out (complaining there's no modules to find in that file) and I had to switch to the syntax that's currently active.

// import Author from "../assets/author.png";
var Author = require("../assets/author.png");

The difference I can imagine is that I'm using TypeScript (transpiling my TSX by awesome-typescript-loader and loading my PNG file-loader) and they seem to use JSX. But as far my understanding goes, it all transpiles to plain JS and require in the end.

Being a noob on React, I'm not sure what the reason of this discrepancy is but also I'm not sure what to google for to investigate myself.

like image 422
DonkeyBanana Avatar asked Sep 18 '18 16:09

DonkeyBanana


1 Answers

This is more of a problem with typescript than webpack itself, you might need to declare modules on a declaration file.

Create a declarations.d.ts

Update your tsconfig.json

"include": [
    "./declarations.d.ts",
],

Put this on that file:

declare module '*.png';

Error might be gone.

like image 155
PlayMa256 Avatar answered Sep 27 '22 19:09

PlayMa256