【问题标题】:import mp3 file in CRA / TypeScript在 CRA / TypeScript 中导入 mp3 文件
【发布时间】:2020-05-12 23:51:57
【问题描述】:

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

我尝试将文件放在与组件相同的文件夹中,以确保避免路径中的拼写错误。但是运气不好...如何导入 mp3 文件?

App.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"]
}

【问题讨论】:

  • var ClickHi = require('file-loader!./sounds/click_hi.mp3'); 这可能会有所帮助。
  • “导入”一个 mp3 文件会是什么样子?您在寻找原始数据吗?

标签: reactjs typescript create-react-app


【解决方案1】:

我通过将音频文件放在public 文件夹中并像这样引用它来修复它:

useEffect(() => {
    sampler.current = new Sampler(
      { A1: `${process.env.PUBLIC_URL}/audio/click_hi.mp3`},
      () => {
          setLoaded(true);
      }
    ).toMaster();
  }, []);

【讨论】:

    【解决方案2】:

    对于仍然遇到此问题的任何人,就像我一样,不想将资产放在公用文件夹中,请这样做,使用“default”:

    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/

    【讨论】:

    • 这不适用于 create-react-app。仍然给我同样的错误。还有什么我需要做的吗?
    • 我让它在 create-react-app 和 TypeScript 中像这样工作。但是你还需要为 mp3 设置一个模块声明。这是我拥有它的地方:github.com/geocarlos/leiamos.
    • 这是我为 mp3 声明模块的地方:github.com/geocarlos/leiamos/blob/master/custom-types/…
    • 啊哈!谢谢!我现在修复了它,只需将 mp3 文件放入公共文件夹即可。这种方法有什么缺点吗?
    • 对我个人而言,这只是组织问题。在开发过程中,我喜欢在 src 文件夹中有资产。
    猜你喜欢
    • 2019-04-12
    • 2018-10-04
    • 2017-06-19
    • 2019-11-15
    • 2022-01-16
    • 2018-05-14
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多