You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript导入PNG图片报错:找不到模块或对应类型声明

问题:TypeScript导入PNG图片提示找不到模块或类型声明

导入代码:

import paySuccessIcon from "@/assets/icons/pay/pay-success.png";

VS Code报错:

Cannot find module '@/assets/icons/pay/pay-success.png' or its corresponding type declarations.ts(2307)
No quick fixes available

已确认PNG文件存在且路径正确,当前Vite配置如下:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'node:path';
import dts from 'vite-plugin-dts';
import { resolve } from 'path';

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        react({
            
        }),
        dts({
            insertTypesEntry: true,
        })
    ],
    build: {
        lib: {
            entry: resolve(__dirname, 'src/index.ts'),
            name: 'rd-component',
            formats: ['es'],
            fileName: (format) => `rd-component.${format}.js`
        },
        assetsDir: 'src/assets',
        sourcemap: true,
        rollupOptions: {
            external: ['react', 'react-dom', 'styled-components'],
            output: {
                globals: {
                    react: 'React',
                    'react-dom': 'ReactDOM',
                    'styled-components': 'styled',
                },
            },
        },
    },
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src')
        }
    }
})

原因分析

TypeScript默认只识别TS/JS相关文件,对于PNG这类静态资源,没有内置的类型声明逻辑,因此会抛出"找不到模块或类型声明"的错误。

解决步骤

  1. 在项目src目录下创建types文件夹,新建assets.d.ts类型声明文件
  2. 在assets.d.ts中添加静态资源的类型声明:
// 声明PNG图片类型
declare module '*.png' {
  const value: string;
  export default value;
}

// 按需添加其他图片格式的声明(可选)
declare module '*.jpg' {
  const value: string;
  export default value;
}

declare module '*.svg' {
  const value: string;
  export default value;
}
  1. 检查tsconfig.json的include配置,确保包含该类型文件:
{
  "include": [
    "src/**/*",
    "src/types/**/*.d.ts"
  ]
}

如果tsconfig.json已经配置了src/**/*,这一步可省略,TS会自动识别src下的.d.ts文件。

完成以上操作后,VS Code的类型错误提示会消失,图片导入可正常使用。


内容的提问来源于stack exchange,提问作者spark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:05:22