reactjs - 在 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"]
}
解决方案
对于仍然有这个问题的任何人,就像我一样,不想将资产放在公用文件夹中,这样做,使用“默认值”:
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/
推荐阅读
- scala - IntelliJ 仅在我选择它时重新格式化代码(对于 Scala)
- android - android.hardware.camera2.CameraAccessException:相机设备已在使用中
- java - 在字符串中的值中查找变量 Android Studio, Java
- java - 使用用于 rest-high-level-client 的 java 代码将完成建议添加到索引
- android - Jackson 在反序列化期间更改日期
- yaml - 在 puppet 模板文件中加密私钥
- http - 通过 HTTP/S 发送数据:base64url 中的二进制或编码?
- elasticsearch - 在弹性搜索中查找与整个查询匹配的文档
- opengl - OpenGL中是否有绘制圆的API?
- docker - docker build --add-host 命令的问题