Reputation: 113
I am trying to add images using import
import image from '../assets/images/picture.jpg
am using Typescript with gatsby ... the strange thing is it works fine with normal javascript (.js ~ .jsx file) but when I use (.ts ~ .tsx file) it throw out this error
Cannot find module '../assets/images/picture.jpg' or its corresponding type declarations.ts(2307)
The strange thing is it works fine with normal components like
import Header from '../components/Header'
here is my tsconfig.json file
{
"compilerOptions": {
"module": "commonjs",
"target": "esnext",
"jsx": "preserve",
"lib": [
"dom",
"es2015",
"es2017"
],
"strict": true,
"noEmit": true,
"isolatedModules": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"preserveConstEnums": true
},
"include": [
"./src/**/*"
]
}
and here is gatsby-config.json file
module.exports = {
/* Your site config here */
plugins: [
{
resolve: `gatsby-plugin-typescript`,
options: {
isTSX: true, // defaults to false
jsxPragma: `jsx`, // defaults to "React"
allExtensions: true, // defaults to false
},
},
],
}
folder Structure
Upvotes: 8
Views: 2052
Reputation: 2373
Create index.d.ts file in folder src, and add this line
declare module "*.jpg"
declare module "*.png"
declare module "*.svg"
Ref: Importing images in TypeScript React - "Cannot find module"
Thanks ferran-buireu for clearing out all queries.
Upvotes: 9
Reputation: 29320
This is redundant:
import Header from '../components/Header'
Because they are in the same folder, you just can:
import Header from './Header'
Regarding the asset, you can follow this similar issue Importing images in TypeScript React - "Cannot find module" to get some ideas but you can easily fix it by:
const image = require('../assets/images/picture.jpg')
Note: I guess it's a typo from the answer but you are missing a trailing quote in the importation at import image from '../assets/images/picture.jpg
<-- here
In addition, try changing back to false the allExtensions
boolean:
allExtensions: false,
Credits to Kyle Mathews
Upvotes: 1