【问题标题】:Importing image in gatsby config fail在 gatsby 配置中导入图像失败
【发布时间】:2020-02-23 11:32:30
【问题描述】:

我有一个带有 Gatbsy 的应用程序,我想在其中加载一系列图像以分配给 siteMetaData

我做了以下gatsby-config.ts

import projects from "./src/data/projects";

module.exports = {
  siteMetadata: {
    projects
  },
  plugins: [
    //...
  ]

我的project.ts基本上是

import * as Image from "./images";

export default [
    {
        title: Image.myImage
    }

而 images.ts 只是导出一系列图像:

import myImagefrom from "./src/images/projects/image.jpg";
export const myImage;

但我在编译时遇到错误

找不到模块“./src/images/projects/image.jpg”。

但如果我点击(点击链接),我确实会在可视代码中看到我的图像...

所以我不明白我做错了什么,我尝试了很多不同的路径,但无法成功。

【问题讨论】:

  • images.ts 中的from 在哪里?
  • 是的,抱歉是因为我剪掉了一些代码以使其更清晰,我忘记了,将添加。但这不是问题
  • 我尝试使用 require,但我得到相同类型的错误```错误:找不到模块 'src/images/projects/image.jpg' Require stack: ```
  • 我也有同样的问题。当我找到解决方案时,我会告诉你。

标签: typescript gatsby


【解决方案1】:

在文件夹 src 中创建 global.d.ts 文件,并添加这一行

    // fix: gatsby typescript error cannot find module img.jpg or its corresponding type declarations
    declare module "*.jpg" {
      export default "" as string;
    }
    declare module "*.png" {
      export default "" as string;
    }
    
  // fix typescript error of not being able to import svgs has react components
    declare module "*.svg" {
      import React = require('react');
      export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
      const src: string;
      export default src;
    }

来源: https://www.codegrepper.com/code-examples/javascript/gatsby+typescript+error+cannot+find+module+img.jpg+or+its+corresponding+type+declarations https://stackoverflow.com/a/54122106/3044126

【讨论】:

  • 别忘了将global.d.ts 添加到tsconfig.json 中的include 数组中
猜你喜欢
  • 1970-01-01
  • 2019-12-11
  • 2017-01-28
  • 1970-01-01
  • 2019-11-21
  • 2017-09-15
  • 2014-09-01
  • 2021-08-08
  • 2019-08-06
相关资源
最近更新 更多