Vue3: The module './assets/logo.png' and its corresponding type declarations are not found

The project was created using the following command:

vue create testtype3

Link to image: https://i.sstatic.net/vMuq0.png

App.vue:

<template>
  <img alt="Vue logo" src="./assets/logo.png">

  <img :src="MyIcon" />

</template>

<script lang="ts">
import { defineComponent } from 'vue';
import MyIcon from './assets/logo.png';


export default defineComponent({
  name: 'App',
  components: {


  },

  setup(props, { emit }) {
    return  {
      MyIcon
    }
  }
});
</script>

main.ts:

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

index.d.ts:

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

babel.config.js:

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ]
}

package.json:

{
  "name": "testtype3",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.4.0",
    "@typescript-eslint/parser": "^5.4.0",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-typescript": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/eslint-config-typescript": "^9.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "file-loader": "^6.2.0",
    "typescript": "~4.5.5"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

vue.config.js:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
})

The App displays a logo in two ways: passing a path String to an img and by passing an imported MyLogo to an img. However, I get an error for the second approach:

TS2307: Cannot find module './assets/logo.png' or its corresponding type declarations.
<script lang="ts">
import { defineComponent } from 'vue';
import MyIcon from './assets/logo.png';
                            ^^^^^^^^^^^^^^^^^^^

Removing the MyIcon import and the img element that uses MyIcon results in npm run serve running without problems.

A types folder was created in the root directory with an added index.d.ts, however the error persists.

Answer №1

To make the necessary changes, follow these steps:

update index.d.ts with the following content:</p>
declare module '*.png' {
  const value: string;
  export = value;
}

Additionally, modify tsconfig.json by including the line below:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@//*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    // don't forget to add this line
    "types/index.d.ts",
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

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

Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function? const func = (x:number, ...

How to include a javascript file in a vuejs2 project

Just starting out with the Vue.js framework and I've hit a snag trying to integrate js libraries into my project. Would greatly appreciate any assistance! By the way, I attempted adding the following code to my main.js file but it didn't have th ...

How can a particular route parameter in Vue3 with Typescript be used to retrieve an array of strings?

Encountered a build error: src/views/IndividualProgramView.vue:18:63 - error TS2345: Argument of type 'string | string[]' is not assignable to parameter of type 'string'. Type 'string[]' is not assignable to type 'strin ...

Transferring functionality from a child component to a parent component

I have a Base Component called ListComponent and a ParentComponent named Businesses2ListComponent. The concept is to have multiple types of Lists with tables that all stem from the ListComponent. This requires passing the correct service accordingly. In t ...

After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to ca ...

unable to assign the disable property to a button element

In the code snippet below, I am working on a child-component. I have created a button and I want to include a disable property. However, the current implementation of the code results in an error message with red underlining indicating: Type '"is ...

TypeScript typings for generic currying functions

I'm struggling to improve my skills in functional programming, particularly when dealing with typing generic "curry" functions. One example is a "Curry" version of the reduce function that I've written: const reduce = <S, R>(fn: (result: R ...

Guide to organizing and performing operations within a loop using vue.js

I have an array called year-month-value containing data retrieved from a Google Sheet: 2019 - Mar - 3 2019 - Mar - 1 2019 - Feb - 1 2019 - Feb - 1 2019 - Feb - 1 2019 - Feb - 1 2019 - Feb - 3 2019 - Feb - 2019 - Feb - 2 2019 - Feb - 1 2019 - Feb - 1 2019 ...

Typescript typings for child model/collection structures

I have encountered an issue while trying to implement a Model/Collection pattern with various typings. Both the Model and Collection classes have a method called serialize(). When this method is called on the Collection, it serializes all the Model(s) with ...

Improprove lazy loading in Vue.js by utilizing webpack chunks. Explore the differences between using import and require-resolve

When it comes to lazy loading with webpack chunks, I've discovered two methods - one involves using require & resolve, and the other involves using import. The require & resolve method: const Home = resolve => { require.ensure(['co ...

Patience is key when awaiting a state update in the Vue.js router's beforeEnter guard

My goal is to control access to specific pages in my vue router. Instead of embedding authentication logic in each component, I would prefer to have a 'hasUserAccess' check in my child-routes only where it's necessary. { path: 'admi ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

Unable to transfer an object into a component due to a subscribe restriction

I have encountered an issue: I am making a post request to save an object in the database. The request takes JSON input with the values of the object to be saved. After saving the object in the database, I need my servlet to return the saved object so that ...

Trouble arises when attempting to transfer cookies between server in Fastify and application in Svelte Kit

In the process of developing a web application, I am utilizing Fastify for the backend server and Svelte Kit for the frontend. My current challenge lies in sending cookies from the server to the client effectively. Despite configuring Fastify with the @fas ...

Having trouble getting Vuejs to work when appending an element to Fullcalender

Hi there, I am facing an issue where appending a custom button to a full calendar event is not working properly with Vue.js methods. It works fine with core JavaScript, but I really want it to work with Vue.js methods. Any ideas on how I can achieve this? ...

The art of interacting with an authenticated API using Axios

I am currently in the process of developing an application using Vue and Laravel. My user authentication is handled by passport within Laravel. However, I am encountering a problem where I receive a 401 unauthorized error when attempting to make a post req ...

Capturing network issues while utilizing apollo-module with Nuxt

Currently, I am utilizing nuxt in conjunction with apollo-module. My main objective is to be able to intercept any potential network errors, specifically 401/403 errors, in order to display an error modal and log out the user. As per the documentation, it ...

Retrieve input from text field and showcase in angular 6 with material design components

Take a look at the output image . In the code below, I am displaying the contents of the messages array. How can I achieve the same functionality with a text box and button in an Angular environment? <mat-card class="example-card"> <mat-car ...

How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error, try { this.doSomething(); } catch (error) { console.error(error); } This problem occurs when "doSomething" returns a promise or runs asynchronous code. doSome ...