Adding mp3 files to a Create React App app

If you’re looking for the steps to include static files, like an mp3, to a create-react-app project — and use es6 import statements to use them in a component, here are the steps. This process will involve “ejecting” from create-react-app, so think about the implications of that before proceeding.

1) Eject from the create-react-app by running npm run eject. The create-react-app documentation describes the eject command

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

2) Include the files you want to use somewhere in the src folder. Probably with the component which will be consuming them.

3) We need to modify our dev and prod webpack configs to allow the files to be import-ed by through webpack and included in the build folder. Add an entry to the exclude list which will test for the file. The exclude list should look like this:

Add a loader to the list of loaders for the file type you want to use:

Do this for both the dev and prod webpack files in the config folder.

3) Within the component file, you can now import the file you with to use, specifying the relative path to the file

4) Then you can use the file within your component. For the example of a mp3 file, you can create a new Audio element in the constructor, and play or pause it using some event handler and function

 

Author: Michael Jasper

Michael is a Web Developer located in Northern Utah. When not programming, he enjoys spending time with his family, exploring the great-outdoors, and hit-and-miss cooking experiments.