Search code examples
reactjsaudiomp3rollupjs

Audio files do not work in a rollup build (react)


I am creating a React library with rollup, I have manage to fix all the other issues I have had but I can not get audio files to work in the build.

In the build dir. I can see the audio files imported in, yet when I run the application which the Library is called, the audio files do not seem to be linked.

I am using @rollup/plugin-url to manage audio files.

here is the Error I am getting in the main application => enter image description here

Importing audio files,

import sound from './Sound.mp3'; 
const play = new Audio(sound);

const SoundCom = ({alive = true}) => {
    const [played, setPlayed] = useState(false);
    
    const playAudio = () => {
        play.play().then(() => {console.log('played!')});
    }

    useEffect(() => {
        if (!played && !alive) {
            playAudio();
            setPlayed(true);
        }
    }, [alive, played])

    return (
        <div className={'main-styles'}>
            .....
        </div>
    ) }

rollup.config.js =>

import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import resolve from 'rollup-plugin-node-resolve'
import scss from 'rollup-plugin-scss'
import json from '@rollup/plugin-json'
import image from 'rollup-plugin-img'
import url from '@rollup/plugin-url'

import pkg from './package.json'

export default {
  input: 'src/index.js',
  output: [
    {
      file: pkg.main,
      format: 'cjs'
    },
    {
      file: pkg.module,
      format: 'es'
    }
  ],
  plugins: [
    babel({
      exclude: 'node_modules/**',
      presets: ['@babel/preset-react']
    }),
    resolve(),
    commonjs({
      namedExports: {
        'node_modules/react-countdown-circle-timer/lib/index.js': [
          'CountdownCircleTimer'
        ]
      }
    }),
    external(),
    scss({
      output: './dist/style.css',
      failOnError: true,
      runtime: require('sass')
    }),
    image({ limit: 100000 }),
    json(),
    url({
      fileName: '[name][extname]',
      include: ['**/*.mp3']
    })
  ],
  external: ['react-dom']
}

Solution

  • For some reason when I added a limit to the url, it start to work.

    In rollup.config.js =>

    export default {
      ....
      plugins: [
        ....
        url({
          fileName: '[name][extname]',
          include: ['**/*.mp3'],
          limit: 100000
        })
      ],
      ....
    }