DEV Community

Molly Gingras
Molly Gingras

Posted on

Loading sound files in Neutrino

Part 2 of a series on my experiences figuring out NeutrinoJS.

I wanted to add sound effects to my app built with Neutrino, using local mp3 and wav files. I know how to do this in plain Webpack — just configure file-loader!

I learned from my previous adventures with style loaders that loaders are often best configured inside any Neutrino preset you're using. So I checked out the docs for the Web preset (whose options are inherited by the other web project presets). There were config options for loading images and fonts, both of which use file-loader under the hood... but nothing for other kinds of files. I would have to dive into webpack-chain configuration.

This sort of configuration is probably simple for more advanced Neutrino users, but I want to document it clearly to make it a little easier for other beginners.

First, don't forget to npm install --save-dev file-loader.

Then, in my .neutrinorc.js I had to add an arrow function to my use array in order to access Neutrino's configuration API. I then was able to use the webpack-chain syntax to tell Webpack (via Neutrino) to find my mp3 and wav files and load them with file-loader, as follows:

module.exports = {
  options: {
    root: __dirname,
  },
  use: [
    standard({
      // ...
    }),
    // It shouldn't matter whether you're using React or other presets here!
    react({
      // ...
    }),
    jest(),
    // Add this arrow function
    (neutrino) => {
      // Access the Neutrino API
      neutrino.config.module
      // Configure whatever you need with the chaining API
      .rule('file')
        // Specify the file types you need here
        .test(/\.(wav|mp3)$/i)
        .pre()
        .use('file')
          // Load those files with file-loader
          .loader('file-loader');
    }
  ],
};

This worked, and now I'm able to import sound files by their paths in my JS files:

import boxingBellWav from './sounds/boxing-bell.wav'

And easily play them with Javascript's built-in Audio() constructor:

const boxingBell = new Audio(boxingBellWav)
boxingBell.play()

... Or, of course, with a full-fledged sound library such as howler.js or SoundJS.

As always, if there's a better way to configure this, I'd love to hear about it! In the meantime I hope this makes someone's Neutrino journey a little smoother.

Top comments (0)