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

如何在React TypeScript组件中导入音频文件?解决模块找不到报错

Fix: Cannot find module './audio/alarm.mp3' in TypeScript React

Hey there, this error pops up because TypeScript doesn’t recognize the type of MP3 files by default—unlike images, which usually come with pre-configured type definitions in most React/TS setups. Let’s fix this step by step:

Step 1: Add a Type Declaration File

First, we need to tell TypeScript how to handle .mp3 imports.

  • In your project’s src directory (or create a types subfolder inside src for cleaner organization), make a new file named audio.d.ts.
  • Paste this code into the file:
    declare module '*.mp3' {
      const src: string;
      export default src;
    }
    
    This tells TypeScript that any .mp3 import will resolve to a string (the file path/URL, just like your working image imports).

Step 2: Check Your TypeScript Config

Make sure your tsconfig.json is set to include this new type file. Verify the include array covers your src folder (and the types folder if you used one):

{
  "compilerOptions": {
    // ... your existing config options
  },
  "include": ["src/**/*"]
}

Step 3: Restart the TypeScript Server

If you’re using VS Code (or another editor with TS support), the server might not pick up the new type file automatically. Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (Mac), search for "TypeScript: Restart TS Server", and run it.

Test the Import

Your import should now work without errors! You can use the audio file just like you would an image:

import alarm from "./audio/alarm.mp3";

function App() {
  return (
    <div>
      <audio src={alarm} controls />
    </div>
  );
}

export default App;

Note: If you’re using Create React App, it technically has built-in support for audio files, but custom configs or older versions can break this—adding the manual type declaration is a reliable fallback.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:54:19