1 year ago
#365675
M -
Dynamically load .mp3s in Vue.js+Nuxt.js on mounted()
I'm tying to follow the official nuxt.js documentation to dynamically load dozens of .mp3 files as the user progresses through a quiz.I've set up my config file as follows:
nuxt.config.js (Nuxt v2.15.8):
build: {
extend ( config, ctx ) {
// Might be used for loading media files
config.module.rules.push({
test: /\.(ogg|mp3|wav|mpe?g)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
});
}
}
This works:
import audioFile from '~/assets/audio/sfx_Q1_1.mp3';
// Outputs /_nuxt/assets/audio/sfx_Q1_1.mp3, and the file plays as expected
console.log(audioFile);
Using an import
statement works, and it gives me the correct asset path. The problem is that I need dozens of mp3s with sfx_Q#_#.mp3
format, so I need a more dynamic approach.
This doesn't work:
mounted() {
let audioURL = `~/assets/audio/sfx_Q${this.qID}_${this.aID}.mp3`;
let audio = require(audioURL);
console.log(audio);
}
With this approach, my app crashes and I get Cannot find module '~/assets/audio/sfx_Q1_1.mp3'
, even though it's exactly the same path as the version that worked with the import
statement.
This also works
<audio v-bind:src="require(`~/assets/audio/sfx_Q${qID}_${aID}.mp3`).default"></audio>
...but this doesn't work
<audio v-bind:src="require(getAudioURL()).default"></audio>
// ... //
getAudioURL() {
return `~/assets/audio/sfx_Q${this.qID}_${this.aID}.mp3`;
}
... I get the same Cannot find module
error. Why does the import break when the file path is generated dynamically inside a method? I've tried with @
symbol as well, to no avail. This question had the same issue, but I've tried exactly the solutions suggested, and it doesn't help.
vue.js
nuxt.js
webpack-file-loader
0 Answers
Your Answer