Using mp3 files in React with Next.js

Tiempo de lectura: < 1 minuto

Today we’re going to learn how to import and use our .mp3 files with Next and React.

When we try to import a .mp3 file, we get this error:

./src/assets/sounds/ .mp3
Module parse failed: Unexpected character '' (1:3)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

Import trace for requested module:
./src/assets/sounds/ .mp3
./src/util/Sound.tsx
./src/components/widgets/perfil/Creditos.tsx
./src/pages/dashboard/[path].tsx

To fix it, we need to install file-loader:

npm i url-loader --save

And configure it inside our module.exports

/** @type {import('next').NextConfig} */

const nextConfig = {
  //distDir: 'build'

  webpack(config, options) {
    config.module.rules.push({
      test: /\.mp3$/,
      use: {
        loader: "url-loader",
      },
    });
    return config;
  },

};

export default nextConfig;

And to prevent TypeScript from causing issues with *.mp3 import, add the following code inside declarations.d.ts (if you don’t have it, create it)

declare module "*.mp3" {
  const src: string;
  export default src;
}

And import it inside tsconfig.json along with the rest of includes.

{
  "include": ["declarations.d.ts"]
}

Leave a Comment