typescript - 带有 Typescript 导入 Assets 错误的 Gatsby (ts2307)

标签 typescript visual-studio-code import gatsby tsconfig

我正在尝试使用 添加图像进口

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
      },
      
    },
  ],
}
文件夹结构
  • 源文件
  • 成分
  • MainComponent.tsx
  • Header.tsx

  • Assets
  • 图片
  • 图片.jpg



  • 最佳答案

    这是多余的:

    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/

    相关文章:

    typescript - 如果文件未打开,Vscode 不会显示 typescript 错误

    node.js - 找不到名称 'require' - Angular 8

    visual-studio-code - Visual Studio 代码看起来很模糊

    java - Wicket 7.6.0 中的 wicket.version.undo 包

    json - LibreOffice Calc 是否支持 JSON 文件导入/排序?

    python - 由于在 python 中找不到模块或模块本身错误导入,区分 ImportError?

    javascript - Typescript - 不同文件中的模块函数引用 - "could not find symbol"

    typescript - 如何将推断的参数连接到用于调用 TypeScript 函数的类型

    python-3.x - VS 代码 : "Property Debug Options Not Allowed"

    visual-studio-code - 在 Visual Studio Code 中的文件选项卡中显示路径