如何在React TypeScript组件中导入音频文件?解决模块找不到报错
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
srcdirectory (or create atypessubfolder insidesrcfor cleaner organization), make a new file namedaudio.d.ts. - Paste this code into the file:
This tells TypeScript that anydeclare module '*.mp3' { const src: string; export default src; }.mp3import 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

