When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules:

/// <reference types="@emotion/react/types/css-prop" />
import '@emotion/react';
import { PureComponent, SVGProps } from 'react';

declare module '*.svg' {
  export class ReactComponent extends PureComponent<SVGProps<SVGSVGElement>> {}
}
declare module '*.ttf';
declare module '*.eot';
declare module '*.woff';
declare module '*.woff2';

Upon running tsc --noEmit, errors like ...

src/fonts/fonts.ts:39:31 - error TS2307: Cannot find module './pt-sans-v12-latin-ext_latin-regular.woff' or its corresponding type declarations.

39 import PTSansregularWOFF from './pt-sans-v12-latin-ext_latin-regular.woff';
                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/fonts/fonts.ts:40:32 - error TS2307: Cannot find module './pt-sans-v12-latin-ext_latin-regular.woff2' or its corresponding type declarations.

40 import PTSansregularWOFF2 from './pt-sans-v12-latin-ext_latin-regular.woff2';
                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/layouts/default/NavigationBar.tsx:4:41 - error TS2307: Cannot find module '../../images/brand.svg' or its corresponding type declarations.

4 import { ReactComponent as Brand } from '../../images/brand.svg';
                                          ~~~~~~~~~~~~~~~~~~~~~~~~

... are displayed.

This is my tsconfig.json:

{
  "include": ["./src/**/*", "./.gatsby/**/*", "./*.ts", "./plugins/**/*"],
  "files": ["./src/types.d.ts"],
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "lib": ["dom", "ES2017", "ES2019"],
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noEmit": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}

This is the structure of my file tree: https://i.stack.imgur.com/Fv1pF.png

How can I ensure Typescript locates the corresponding type declarations?

Interestingly, defining the interface Theme in @emotion/react within my types.d.ts has an effect on other parts.

Answer №1

This is how I utilize it:

declare module '*.jpg';
declare module '*.png';
declare module '*.woff2';
declare module '*.woff';
declare module '*.ttf';

declare module '*.svg' {
  import React = require('react');

  export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
  const src: string;
  export default src;
}

Then, I incorporate it in this manner:

import { ReactComponent as Icon } from './icons/icon.svg';
import AnotherImage from './images/header.jpg';

Answer №2

In order to allow the loading of svg and png files, I added the following snippet to a file named custom.d.ts located in the root directory of the project:

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
      SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;

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

Although I am not an expert, this code snippet appears to define how TypeScript should handle imports of SVG and PNG files within the project.

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

The async/await feature in Typescript fails to trigger updates in the AngularJS view

Currently, I am utilizing Typescript 2.1 (developer version) to transpile async/await to ES5. An issue I have encountered is that when I modify any property linked to the view within my async function, the view does not automatically reflect the updated v ...

Nativescript encountered an error regarding faker: module './address' not found

Currently in the process of learning nativescript, I am experimenting with using faker to generate some data while working with typescript. Here are the versions I am using: Node - 6.9.4 Faker - 3.1.0 Typescript - 2.1.4 Encountered an error which i ...

Altering the properties of a specified element within TestBed using the overrideComponent method

We are implementing TestBed.overrideComponent() to substitute a component with custom behavior. TestBed.overrideComponent(CoolComponent, { set: { template: '<div id="fake-component">i am the fake component</div>', sel ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

The ts-node encountered an issue with the file extension in this message: "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension

When using ts-node, I encountered the following error: $ ts-node index.ts TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts I attempted to remove "type": "module& ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

Error in syntax: The tailwind import statement contains an unrecognized word and will not function correctly

After configuring Tailwind CSS with Next.js, I made changes to the tailwind.config.js file. However, after making these changes, the compilation process failed and resulted in the following error: Error - ./src/assets/styles/global.css:3:1 Syntax error: Un ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice I am developing an angular application that fetches data from an API and presents it on the page The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls apiservice.service.ts ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

The data type 'string | boolean | null' cannot be assigned to type 'boolean'. Specifically, the type 'null' cannot be assigned to type 'boolean'

Can you spot the issue in this code snippet? isAuthenticated(): boolean { var token = localStorage.getItem(ACCESS_TOKEN_KEY); return token && !this.jwtHelper.isTokenExpired(token); } Error: The variable is returning a type of 'string | bo ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

In Typescript, null values are allowed even when the type is set to be non-nullable

Can someone explain why the code below allows for null in typescript, even though number is specified as the type: TS playground // Not sure why null is accepted here when I've specified number as the type const foo = (): number => 1 || null ...

Use a pipe to show the content of the md-input

In my Angular 2 Material application, I have a form that includes a price input: <md-input [(ngModel)]="price" placeholder="Price"> </md-input>{{price|customCurrency}} This input field uses a custom version of the CurrencyPipe which you c ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

TypeScript's type 'T' has the potential to be instantiated with any type, even if it is not directly related to 'number'

Let's say we have a function that takes a value (for example, number) and a callback function that maps that value to another value. The function simply applies the provided callback: function mapNumber<T>(value: number, mapfn: (value: number) = ...