我正在尝试使用 添加图像进口
import image from '../assets/images/picture.jpg
我在 gatsby 中使用 Typescript ......奇怪的是 它适用于普通的 javascript ( .js ~ .jsx 文件 )但是当我使用( .ts ~ .tsx 文件 )它抛出这个错误Cannot find module '../assets/images/picture.jpg' or its corresponding type declarations.ts(2307)
奇怪的是它适用于普通组件,如
import Header from '../components/Header'
这是我的 tsconfig.json 文件{
"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/**/*"
]
}
这是 gatsby-config.json 文件 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
},
},
],
}
文件夹结构 最佳答案
这是多余的:
import Header from '../components/Header'
因为它们在同一个文件夹中,所以您可以:import Header from './Header'
关于 Assets ,你可以关注这个类似的问题 Importing images in TypeScript React - "Cannot find module"获得一些想法,但您可以通过以下方式轻松解决它:const image = require('../assets/images/picture.jpg')
注意:我猜这是答案中的一个错字,但您在 import image from '../assets/images/picture.jpg
的导入中缺少尾随引号<--这里此外,尝试将
allExtensions
改回 false bool 值: allExtensions: false,
致 Kyle Mathews
关于typescript - 带有 Typescript 导入 Assets 错误的 Gatsby (ts2307),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66997415/