Next.js 11+Webpack 5环境导入mp3文件提示找不到模块问题求助
解决方案
1. 补充mp3资源的TypeScript类型声明
你遇到的报错属于TypeScript类型检查阶段抛出的错误,不是webpack打包错误。TS默认不识别非代码类资源的导入,需要手动声明模块类型:
- 在项目根目录创建
@types/media.d.ts文件,写入以下内容:
declare module '*.mp3' { const src: string; export default src; }
- 检查
tsconfig.json中的include配置,确保包含@types目录,示例配置:
{ "compilerOptions": { // 其他配置保持不变 "typeRoots": ["./node_modules/@types", "./@types"] }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "@types/**/*.d.ts"] }
2. 修正webpack配置
你现有配置存在两个问题:
- 拼写错误:
incluse属性不存在,应为include - webpack5已内置asset资源处理能力,无需额外安装
file-loader,更适配Next.js的打包逻辑,推荐替换为以下配置:
const path = require('path') const SRC = path.resolve(__dirname, 'public/sounds/') module.exports = { webpack: (config) => { config.module.rules.push({ test: /\.mp3$/, include: SRC, type: 'asset/resource', generator: { filename: 'static/sounds/[name].[contenthash][ext]' } }) return config } }
注意:不要将输出路径设置为
public/目录,Next.js的public目录是存放静态源文件的位置,打包后的静态资源会统一输出到.next/static目录下,上述配置会自动处理资源的引入路径。
3. 校验导入路径
如果你的tsconfig.json没有配置baseUrl: ".",将绝对导入改为相对路径即可,比如导入文件位于pages目录下,写法为:
import sound_bighit from '../public/sounds/bighit.mp3'
内容的提问来源于stack exchange,提问作者lsc
相关产品推荐
相关产品推荐

