【问题标题】:mp3 files in Webpack 5 w/ Nextjs带有 Nextjs 的 Webpack 5 中的 mp3 文件
【发布时间】:2021-11-19 01:01:29
【问题描述】:

我目前正在使用 next@11.1.2 和 webpack v5 并在修复 mp3 加载时卡住了几个小时。我从堆栈和 GitHub 尝试了其他几种解决方案。它们都不适合我。

Type error: Cannot find module 'public/sounds/bighit.mp3' or its corresponding type declarations.

  14 | 
  15 | // Assets
> 16 | import sound_bighit from "public/sounds/bighit.mp3"
     |                          ^
info  - Checking validity of types .%       

这是我对 webpack 的最后一次配置:

const path = require('path')
const SRC = path.resolve(__dirname, 'public/sounds/')

module.exports = {
    webpack: (config, { }) => {

        config.module.rules.push({
            test: /\.mp3$/,
            incluse: SRC,
            use: {
                loader: 'file-loader',
                options: {
                    name: '[name].[contenthash].[ext]',
                    outputPath: 'public/sounds/',
                    publicPath: 'public/sounds/'
                }
            }

        })

        // config.module.rules.push({
        //     test: /\.mp3$/,
        //     use: {
        //         loader: 'file-loader',
        //     },
        // })

        // config.module.rules.push({
        //     test: /\.mp3/,
        //     use: {
        //         loader: 'url-loader',
        //     },
        // })

        return config
    }
}

【问题讨论】:

    标签: reactjs typescript webpack next.js webpack-5


    【解决方案1】:

    无需导入此类文件。 Next.js 支持将资产放在public 文件夹中。删除您的自定义 webpack 配置,然后简单地执行以下操作:

    <audio controls src="/sounds/bighit.mp3" />
    

    参考:Static File Serving

    Next.js 可以在根目录中名为 public 的文件夹下提供静态文件,例如图像。然后,您的代码可以从基本 URL (/) 开始引用 public 中的文件。


    另外,您遇到的错误是 TypeError,您可以尝试修复它:

    // types/sounds.d.ts
    
    declare module "*.mp3" {
      const content: string;
      export default content;
    }
    

    参考:Importing Other Assets | TypeScript - webpack

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2021-03-21
      • 2021-06-19
      • 2018-06-30
      • 2022-11-28
      相关资源
      最近更新 更多