How to extend Webpack to load audio files?

Audio files should be processed by file-loader. This loader is already included in the default Webpack configuration, but it is not set up to handle audio files. You need to extend its default configuration in nuxt.config.js:

  1. export default {
  2. build: {
  3. extend (config, ctx) {
  4. config.module.rules.push({
  5. test: /\.(ogg|mp3|wav|mpe?g)$/i,
  6. loader: 'file-loader',
  7. options: {
  8. name: '[path][name].[ext]'
  9. }
  10. })
  11. }
  12. }
  13. }

You can now import audio files like this <audio :src="require('@/assets/water.mp3')" controls></audio>.

If you only want to write: <audio src="@/assets/water.mp3" controls></audio>, you need to tell vue-loader to automatically require your audio files when you reference them with the src attribute:

  1. export default {
  2. build: {
  3. loaders: {
  4. vue: {
  5. transformAssetUrls: {
  6. audio: 'src'
  7. }
  8. }
  9. },
  10. extend (config, ctx) {
  11. config.module.rules.push({
  12. test: /\.(ogg|mp3|wav|mpe?g)$/i,
  13. loader: 'file-loader',
  14. options: {
  15. name: '[path][name].[ext]'
  16. }
  17. })
  18. }
  19. }
  20. }