首页 > 解决方案 > 在 CRA / TypeScript 中导入 mp3 文件

问题描述

我有一个内置 CRA 的简单应用程序v3.2.0。我使用默认设置的 TypeScript(见tsconfig.ts下文)。在/src/sounds/我有一个要在组件中使用的 mp3 文件“click_hi.mp3”,但我无法导入带有错误的 mp3 Cannot find module 'sounds/click_hi.mp3'.ts(2307)

我尝试将文件放在与组件相同的文件夹中,以确保避免路径中的拼写错误。但没有运气......我怎样才能导入 mp3 文件?

应用程序.tsx

import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import { Sampler } from "tone";
import ClickHi from 'sounds/click_hi.mp3'


export default function ExercisePage() {
  const [isLoaded, setLoaded] = useState(false);
  const sampler = useRef(null);

  useEffect(() => {
    sampler.current = new Sampler(
      { "A1": ClickHi },
      {
        onload: () => {
          setLoaded(true);
        }
      }
    ).toMaster();
  }, []);

  const handleClick = () => sampler.current.triggerAttack("A1");

  return (
    <div>
      <button disabled={!isLoaded} onClick={handleClick}>
        start
      </button>
    </div>
  );
}

tsconfig.ts

{
  "compilerOptions": {
    "baseUrl": "src",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["src"]
}

标签: reactjstypescriptcreate-react-app

解决方案


对于仍然有这个问题的任何人,就像我一样,不想将资产放在公用文件夹中,这样做,使用“默认值”:

const path = require('../assets/audio/some_audio.mp3');
setAudio(new Audio(path.default));

注意:我只在使用 TypeScript 时遇到过这个问题。您需要为 mp3 声明一个模块,方法是在您的项目 src 文件夹中添加一个名为“audio.d.ts”的文件,内容如下declare module '.*mp3';

简单应用程序工作示例,使用此:https ://geocarlos.github.io/leiamos/


推荐阅读