Error TS2307: Module './images/logo.png' could not be located

I encountered an issue while attempting to import a local png image into my ts webpack project. The error message displayed was as follows:

TS2307: Cannot find module './images/logo.png'.

All other modules, such as css, svg, and ts files, import successfully without any errors. This problem appears to be specific to png files.

Here is the configuration in my webpack.config.js file:

module: {
    rules: [{
      test: /\.ts$/,
      use:['ts-loader']
    },{
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },{
      test: /\.(woff|woff2|eot|ttf|svg)$/,
      use: ['url-loader?limit=100000']
    },{
      test: /\.png$/,
      use: ['file-loader']
    }]
  }

Below is my tsconfig.json setup:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "module": "CommonJS",
    "target": "ES5",
    "lib": ["DOM", "ES2015.Promise", "ES5"],
    "allowJs": true,
    "alwaysStrict": true
  }
}

The import statement causing the error is:

import Logo from './images/logo.png';

My file structure looks like this:

root
-src
--css
--images
---logo.png
--index.ts
--templates.ts
-package.json
-tsconfig.json
-webpack.config.js

Answer №1

I discovered the solution on this informative source. Webpack & Typescript image import

Here is the approach I took.

Created a new folder and an import-png.d.ts file

root
-typings
--custom
---import-png.d.ts

import-png.d.ts

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

modified my file-loader configuration to this:

{
      test: /\.(png|jpe?g|gif|jp2|webp)$/,
      loader: 'file-loader',
      options: {
        name: 'images/[name].[ext]'
      }

now, I can perform imports using a syntax like:

import Logo from './images/logo.png'

Answer №2

I made a mistake by forgetting to include the reference react-app-env.d.ts:

/* eslint-disable spaced-comment */
/// <reference types="react-scripts" />

Eslint required me to add this line due to the spaced-comment rule.

Hopefully, this information proves useful to someone else.

Answer №3

To add a new file to the images folder, simply create a file named images.d.ts and insert the following code:

declare module "*.png" {

  export default value: any;

}

Answer №4

To add TypeScript support in your project, simply create a new d.ts file at the root folder and paste the following line:

 declare module '*'

After saving the changes, restart VScode and you're all set!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...

ReactJS: Error - Attempting to convert an undefined or null value to an object is not

Encountering an issue with my Beach component, which is throwing the following error: TypeError: Cannot convert undefined or null to object ResortDetail C:/Users/JS/Desktop/MERN/KR/frontend/src/screens/Beach.js:33 30 | <p>{description}< ...

Save only the most recent iteration of the javascript file in the cache

I've encountered an issue with browser caching of JavaScript files, even though I've utilized FileETag MTime Size in my htaccess file to verify the modified time and size for detecting the latest version. My current method of including JavaScri ...

"Exploring the possibilities of the Raphael JavaScript Library on an iPhone

I've been trying to integrate the Raphael JavaScript library into my iPhone project, but I'm running into an issue with getting it to work in a webview. On Safari for Mac, everything seems fine and I can see the red circle as expected. However, w ...

Determined Worth of Chosen <Datalist> Option

Currently, I am utilizing an <input type='text'> Element in conjunction with a <datalist> to suggest user names for a form. The functionality is working correctly and all my users are displayed. However, upon form submission, I need ...

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...

Execute function when multiple computed properties are true / filled (VueJS)

I am looking to execute a function in my methods section only when all three variables, test1, test2, and test3, are populated. If any of them are empty, I want nothing to happen. I have attempted to achieve this using computed properties and then with a ...

Insert a fresh item to the end of the scrollable container

My goal is to dynamically add a div to the bottom of another div by using a JavaScript button click event. However, I have encountered an issue where once the outer container reaches its maximum height, the list no longer scrolls to the bottom after adding ...

Steps for updating a specific item within an object in an array of MongoDB document

Consider the following data collection, for which I have some questions: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { ...

What is the best way to manage two different IDs, one using jQuery and the other using Vue.js?

How can I manage to include a sliding effect for my products using jQuery ID and display items with Vue.js? <script type="text/javascript> $(window).load(function() { $("#flexiselDemo1").flexisel({ ....................... ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

Why does the Roman to Integer conversion in JS only convert the first character?

Struggling with Leedcode question 13: Given a roman numeral, convert it to an integer. The input is guaranteed to be within the range from 1 to 3999. I've written some code below, but I'm puzzled as to why it only converts the first character in ...

"Glitch in Yahoo Gifshot JavaScript causing issues with frame numbering

I have been using the Yahoo gifshot library to generate gifs from videos. A user uploads a video, and I use this library to dynamically create a gif from that video. However, the issue arises when a user uploads a two-second video but the resulting gif is ...

Looking to switch up the thumbs-up button design?

I am a beginner in using jquery and ajax, and I need some assistance. How can I incorporate this jquery code into my logic: $('.btn-likes').on('click', function() { $(this).toggleClass('liked'); }); Can so ...

The sorting of objects by Lodash is not accurate

My aim is to arrange objects based on a specific property (price). var arr = [{ name: 'Apple', price: '1.03' }, { name: 'Cherry', price: '0.33' }, { name: &apo ...

Sending ASP.NET Components to JavaScript Functions

I've set up a text box and label in the following way: <asp:TextBox ID="MyTextBox" runat="server"/> <asp:Label ID="MyLabel" runat="server"/> Additionally, I've created a JavaScript function like this: function checkLength(myTex ...

Dilemma arises from conflicting javascript codes

Currently, I am developing a web application where the main page features a timeline that needs to update its content automatically. To achieve this, I am utilizing the setTimeOut function of JQuery to refresh the timeline every x seconds. In addition, th ...

Can an XSS attack occur on a style tag with inline styling?

For example: <!DOCTYPE html> <html lang="en"> <head> <title>Test for Potential XSS Attack</title> <style> div { background-color:blue; height:120px; ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Can you tell me about some commonly used GUI widgets in Servlet-JSP?

I am new to working with Servlets, Tomcat, JSP, and I am curious about the common practices for incorporating GUI elements into JSP pages to enhance client-side interactivity. I have experience with jQuery, YUI, extJS, among others, for JavaScript scriptin ...